簡體   English   中英

通過反射獲取帶有“in”參數的方法

[英]Get method with an 'in' parameter through reflection

想象一下以下場景,您希望獲取第一個方法的MethodInfo

public class Foo
{
    public void Bar(in int value)
    {
    }

    public void Bar(string value)
    {
    }
}

如果我們現在查看typeof(Foo).GetMethods(BindingFlags.Public | BindingFlags.Instance)的 output :

MethodInfo[6] { [Void Bar(Int32 ByRef)], [Void Bar(System.String)], [Boolean Equals(System.Object)], [Int32 GetHashCode()], [System.Type GetType()], [System.String ToString()] }

您可以看到第一個方法,即我們要獲取MethodInfo的方法,它說Int32 ByRefInt32類型不同。 我顯然嘗試了以下方法,但沒有任何成功:

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)"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM