[英]Reflection on a static overloaded method using an out parameter
我有一些問題,通過反射調用帶有out參數的重載靜態方法,並會欣賞一些指針。
我想動態創建類似System.Int32
或System.Decimal
的類型,然后在其上調用靜態TryParse(string, out x)
方法。
以下代碼有兩個問題:
t.GetMethod("TryParse", new Type[] { typeof(string), t } )
無法返回我期望的MethodInfo
mi.Invoke(null, new object[] { value.ToString(), concreteInstance })
似乎成功但沒有將out param concreteInstance
設置為已解析的值
交織到此函數中,您可以看到一些臨時代碼,演示如果type
參數設置為System.Decimal
會發生什么。
public static object Cast(object value, string type)
{
Type t = Type.GetType(type);
if (t != null)
{
object concreteInstance = Activator.CreateInstance(t);
decimal tempInstance = 0;
List<MethodInfo> l = new List<MethodInfo>(t.GetMethods(BindingFlags.Static | BindingFlags.Public));
MethodInfo mi;
mi = t.GetMethod("TryParse", new Type[] { typeof(string), t } ); //this FAILS to get the method, returns null
mi = l.FirstOrDefault(x => x.Name == "TryParse" && x.GetParameters().Length == 2); //ugly hack required because the previous line failed
if (mi != null)
{
try
{
bool retVal = decimal.TryParse(value.ToString(), out tempInstance);
Console.WriteLine(retVal.ToString()); //retVal is true, tempInstance is correctly set
object z = mi.Invoke(null, new object[] { value.ToString(), concreteInstance });
Console.WriteLine(z.ToString()); //z is true, but concreteInstance is NOT set
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
return concreteInstance;
}
return value;
}
我需要做些什么來確保我的t.GetMethod()
調用返回正確的MethodInfo? 我需要做什么做有concreteInstance
在我的設置正確mi.Invoke()
調用?
我知道有很多關於這個主題的問題,但是大多數都涉及靜態泛型方法或沒有重載的靜態方法。 這個問題類似但不重復。
您需要使用正確的BindingFlags
並使用Type.MakeByRefType
作為out
和ref
參數。 一秒鍾,我將為您提供代碼示例。
例如,
MethodInfo methodInfo = typeof(int).GetMethod(
"TryParse",
BindingFlags.Public | BindingFlags.Static,
Type.DefaultBinder,
new[] { typeof(string), typeof(int).MakeByRefType() },
null
);
我應該指出,調用它也有點棘手。 這是你如何做到的。
string s = "123";
var inputParameters = new object[] { "123", null };
methodInfo.Invoke(null, inputParameters);
Console.WriteLine((int)inputParameters[1]);
第一個null
是因為我們正在調用靜態方法(沒有對象“接收”此調用)。 inputParameters
的null
將由TryParse
“填充”給我們解析的結果(它是out
參數)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.