通过反射获取具有"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)"

最新更新