c# - 通过反射获取带有“in”参数的方法
问题描述
想象一下以下场景,您希望在其中获取MethodInfo
第一种方法:
public class Foo
{
public void Bar(in int value)
{
}
public void Bar(string value)
{
}
}
如果我们现在看一下输出typeof(Foo).GetMethods(BindingFlags.Public | BindingFlags.Instance)
:
MethodInfo[6] { [Void Bar(Int32 ByRef)], [Void Bar(System.String)], [Boolean Equals(System.Object)], [Int32 GetHashCode()], [System.Type GetType()], [System.String ToString()] }
你可以看到第一个方法,我们想要得到的那个MethodInfo
,它说Int32 ByRef
的和类型不一样Int32
。我显然尝试了以下方法,但没有任何成功:
typeof(Foo).GetMethod("Bar", BindingFlags.Public | BindingFlags.Instance, null, new[] { typeof(int) }, null)
我使用以下代码仔细查看了实际参数:
typeof(Foo).GetMethods(BindingFlags.Public | BindingFlags.Instance)[0].GetParameters()[0]
哪个输出[Int32& value]
,看起来像值类型的指针。那么有什么方法可以Int32&
在运行时获取类型吗?类似的东西typeof(Int32&)
?
解决方案
你应该使用MakeByRefType
:
Console.WriteLine(
typeof(Foo).GetMethod("Bar", new[] { typeof(int).MakeByRefType() })
);
// prints "Void Bar(Int32 ByRef)"
推荐阅读
- mysql - Laravel 5.6 中的控制器继承
- timer - STM32F4 定时器 - 计算周期和预分频,并产生 1 ms 延迟
- jquery - 使用 jquery 的多个复选框过滤器
- javascript - 错误:找不到模块“socket.io-client/dist/socket.io.min.js”
- iphone - 多部分/表单数据操作请求在 iPhone Liferay 7 上不起作用
- processing - 找到柏林噪声的斜率
- javascript - React Router v4 - 切换组件时保持滚动位置
- python - TensorFlow InvalidArgumentError/Value 错误发生与代码的微小变化
- c# - 引导警报显示在 asp.net 中的页面加载时
- angularjs - 如何在角度电话猫中运行量角器测试?