反思:如何获得一个通用的方法是什么? [英] Reflection: How to get a generic method?
本文介绍了反思:如何获得一个通用的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能显示的文件:结果
选择权泛型方法
如何使用反射来调用泛型方法?结果
与反射
块引用>您好
让我们说我有一个类中的两个以下两种方法:
公共无效的MyMethod(VAL对象){}
公共无效的MyMethod< T>(T VAL){}与反思,我能得到这样的第一种方法:
键入[] = typeArray新型[1];
typeArray.SetValue(typeof运算(对象),1);
。VAR myMethod的= myInstance.GetType()实现getMethod(的MyMethod,typeArray);但我怎么能拿到第二,泛型方法?
解决方案VAR myMethod的= myInstance.GetType()
.GetMethods()
。凡(M = GT; m.Name ==的MyMethod)
。选择(M =>新建{
方法= M,
PARAMS = m.GetParameters()
ARGS = m.GetGenericArguments()
})
。凡(X => x.Params.Length == 1
&功放;&安培; x.Args.Length == 1
&功放;&安培; x.Params [0] .ParameterType == x.Args [0])
。选择(X => x.Method)
。第一();Possible Duplicates:
How to use reflection to call generic Method?
Select Right Generic Method with ReflectionHi there
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屋!
查看全文