可能的重复:
如何使用反射调用泛型方法? https://stackoverflow.com/questions/232535/how-to-use-reflection-to-call-generic-method
通过反射选择正确的通用方法 https://stackoverflow.com/questions/3631547/select-right-generic-method-with-reflection
Hi there
假设我在一个类中有以下两个方法:
public void MyMethod(object val) {}
public void MyMethod<T>(T val) {}
经过反思,我可以得到第一个方法,如下所示:
Type[] typeArray = new Type[1];
typeArray.SetValue(typeof(object), 1);
var myMethod = myInstance.GetType().GetMethod("MyMethod", typeArray);
但是我怎样才能获得第二种通用方法呢?
var myMethod = myInstance.GetType()
.GetMethods()
.Where(m => m.Name == "MyMethod")
.Select(m => new {
Method = m,
Params = m.GetParameters(),
Args = m.GetGenericArguments()
})
.Where(x => x.Params.Length == 1
&& x.Args.Length == 1
&& x.Params[0].ParameterType == x.Args[0])
.Select(x => x.Method)
.First();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)