[英]How to find an overloaded method by reflection
This is a question associated with another question I asked before . 这是我之前问过的另一个问题 。 I have an overloaded method:
我有一个重载的方法:
public void Add<T>(SomeType<T> some) { }
public void Add<T>(AnotherType<T> another) { }
How can I find each method by reflection? 如何通过反射找到每种方法? eg How can I get the
Add<T>(SomeType<T> some)
method by reflection? 例如,如何通过反射获取
Add<T>(SomeType<T> some)
方法? Can you help me please? 你能帮我吗? Thanks in advance.
提前致谢。
The trick here is describing that you want the parameter to be SomeType<T>
, where T
is the generic type of the Add
method. 这里的技巧是描述您希望参数为
SomeType<T>
,其中T
是Add
方法的通用类型。
Other than that, it's just about using standard reflection, like CastroXXL suggested in his answer. 除此之外,它只是使用标准反射,就像CastroXXL在他的答案中建议的那样。
Here's how I did it: 这是我的操作方式:
var theMethodISeek = typeof(MyClass).GetMethods()
.Where(m => m.Name == "Add" && m.IsGenericMethodDefinition)
.Where(m =>
{
// the generic T type
var typeT = m.GetGenericArguments()[0];
// SomeType<T>
var someTypeOfT =
typeof(SomeType<>).MakeGenericType(new[] { typeT });
return m.GetParameters().First().ParameterType == someTypeOfT;
})
.First();
Look into the MethodInfo Members: http://msdn.microsoft.com/en-US/library/system.reflection.methodinfo_members(v=vs.80).aspx 查看MethodInfo成员: http : //msdn.microsoft.com/zh-CN/library/system.reflection.methodinfo_members( v=vs.80) .aspx
There are helper properties for IsGenericMethodDefinition
and GetParameters
. 有
IsGenericMethodDefinition
和GetParameters
帮助程序属性。 Both could help you figure out what function is what. 两者都可以帮助您找出什么功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.