反思:如何获取泛型方法? [英] Reflection: How to get a generic method?
本文介绍了反思:如何获取泛型方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能的重复:
如何使用反射调用泛型方法?
使用反射选择正确的泛型方法
你好
假设我在一个类中有两个以下两个方法:
Let's say I have two following two methods in a class:
public void MyMethod(object val) {}
public void MyMethod<T>(T val) {}
通过反射,我可以得到这样的第一个方法:
With reflection, I could get the first Method like this:
Type[] typeArray = new Type[1];
typeArray.SetValue(typeof(object), 1);
var myMethod = myInstance.GetType().GetMethod("MyMethod", typeArray);
但是我怎样才能获得第二种通用方法?
But how can I get the second, generic method?
推荐答案
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();
这篇关于反思:如何获取泛型方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文