使用out参数反映静态重载方法

我有一些问题,通过reflection调用带有out参数的重载静态方法,并会欣赏一些指针。

我想要动态创建类似System.Int32System.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 l = new List(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? 我需要做什么才能在我的mi.Invoke()调用中正确设置mi.Invoke()

我知道关于这个主题有很多问题,但是大多数都涉及静态generics方法或没有重载的静态方法。 这个问题类似但不重复。

您需要使用正确的BindingFlags并使用Type.MakeByRefType作为outref参数。 一秒钟,我将为您准备一个代码示例。

例如,

 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是因为我们正在调用静态方法(没有对象“接收”此调用)。 inputParametersnull将由TryParse “填充”给我们解析的结果(它是out参数)。