首页 > 解决方案 > 通过反射获取带有“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&)

标签: c#reflection

解决方案


你应该使用MakeByRefType

Console.WriteLine(
    typeof(Foo).GetMethod("Bar", new[] { typeof(int).MakeByRefType() })
);

// prints "Void Bar(Int32 ByRef)"

推荐阅读