如何获得MethodInfo的通用扩展方法? [英] How to get MethodInfo for generic extension method?
问题描述
我有一个 IEnumerable< T>
,我想调用 Enumerable.Contains
方法。我只是努力争取正确的语法。这是我现在有的:
I have an IEnumerable<T>
, and I want to call the Enumerable.Contains
method by reflection. I'm just struggling to get the syntax right. Here's what I currently have:
var containsMethod = typeof(Enumerable).GetMethod("Contains",
new[] {
typeof(IEnumerable<T>),
typeof(T)
});
这只是返回null。
获取 MethodInfo
?
推荐答案
的正确方法是什么?
获取MethodInfo的正确方法是什么?
What is the correct way to get the MethodInfo?
您必须找到 / em>方法 - 这不幸有点痛苦 - 然后用适当的参数构造它。在这种情况下,您知道只有2 Contains
重载,并且您想要的重载有两个参数,因此您可以使用:
You have to find the generic method - which is unfortunately a bit of a pain - and then construct that with the appropriate arguments. In this case you know that there are only 2 Contains
overloads, and the one you want has two arguments, so you can use:
var method = typeof(Enumerable).GetMethods()
.Where(m => m.Name == "Contains")
.Single(m => m.GetParameters().Length == 2)
.MakeGenericMethod(typeof(T));
然后,您应该可以适当地调用它。
You should then be able to invoke it appropriately.
这篇关于如何获得MethodInfo的通用扩展方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!