c# - 如何使用 Type.GetMethod(string name, int genericParameterCount, Type[] types) 获取通用 MethodInfo?
问题描述
我正在尝试获取MethodInfo
特定方法Interlocked.CompareExchange<T>(ref T, T, T)
并尝试以下代码无济于事:
typeof(Interlocked).GetMethod(nameof(Interlocked.CompareExchange), 1, new Type[] { typeof(int), typeof(int), typeof(int) })
请注意,这typeof(int)
只是一种随机类型。我所需要的只是MethodInfo
这样我以后可以使用GetGenericMethodDefinition
不同的类型。
我们应该传递什么类型的数组来获取所需的方法?
解决方案
解决方案非常简单:
Type genericType = Type.MakeGenericMethodParameter(0);
Type[] types = new Type[] { genericType.MakeByRefType(), genericType, genericType };
MethodInfo methodInfo = typeof(Interlocked).GetMethod(nameof(Interlocked.CompareExchange), 1, types);
推荐阅读
- nativescript - 如何在 nativeScript 中捕获滚动偏移 RadListVIew?
- c# - 有没有办法让比较更短
- android - 打开创建新图像资源时出错
- android - Admob Adreward 加载失败,错误代码 0
- java - 你知道 Java 8 格式化程序将链式调用放在单独的行中吗?
- angular - 如何从另一个 [Angular] 调用一个组件的方法
- javascript - 我怎样才能制作一个水平的,两个方向,(好像身体是一个 360 度水平面),用 javascript 滚动身体?
- angular - 单选输入和同时输入的默认值
- javascript - 我的蜘蛛网周围有一个奇怪的圆圈,我该如何解决?
- regex - 使用颤振飞镖从字符串中提取 JSON