使用out参数反映静态重载方法
我有一些问题,通过reflection调用带有out参数的重载静态方法,并会欣赏一些指针。
我想要动态创建类似System.Int32
或System.Decimal
的类型,然后在其上调用静态TryParse(string, out x)
方法。
以下代码有两个问题:
交织到此函数中,您可以看到一些临时代码,演示如果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
作为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
参数)。
上述就是C#学习教程:使用out参数反映静态重载方法分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1003776.html