我在通过反射调用带有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参数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()
需要做些什么?
我知道关于这个主题有很多问题,但是大多数都涉及静态泛型方法或没有重载的静态方法。 This question类似但不重复。
答案 0 :(得分:27)
您需要使用正确的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
是因为我们正在调用静态方法(没有对象“接收”此调用)。 null
中的inputParameters
TryParse
将由out
填充给我们,并带有解析结果({{1}}参数)。