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