c# - 如何获取通用扩展方法的 MethodInfo?

标签 c# linq generics reflection extension-methods

我有一个 IEnumerable<T> , 我想调用 Enumerable.Contains 反射法。我只是在努力使语法正确。这是我目前拥有的:

var containsMethod = typeof(Enumerable).GetMethod("Contains", 
  new[] {
    typeof(IEnumerable<T>), 
    typeof(T) 
  });

这只是返回一个 null。

获取 MethodInfo 的正确方法是什么? ?

最佳答案

What is the correct way to get the MethodInfo?

您必须找到通用 方法——不幸的是这有点麻烦——然后用适当的参数构造它。在这种情况下,您知道只有 2 个 Contains 重载,而您想要的重载有两个参数,因此您可以使用:

var method = typeof(Enumerable).GetMethods()
                               .Where(m => m.Name == "Contains")
                               .Single(m => m.GetParameters().Length == 2)
                               .MakeGenericMethod(typeof(T));

然后您应该能够适本地调用它。

关于c# - 如何获取通用扩展方法的 MethodInfo?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17570910/

相关文章:

c# - 时间跨度比较

linq - Resharper 9 转换为 LINQ : method syntax

时间:2019-03-17 标签:c#linqOrderByDescending withinnerLastOrDefault

swift - Swift 上的通用 Equatable 类

java - 将 Collection 和 Iterator 接口(interface)实现为内部类

c# - 如何在 C# 中等待 3 秒然后将 bool 设置为 true?

c# - 如何调出内置文件复制对话框?

c# - 正则表达式匹配以提取多行文本区域 (C#)

linq - 最有效的 Entity Framework 代码优先方法,用于展平/投影具有特定子实体的父实体

scala - 无法在 Scala 中编写同时适用于 Double 和 Float 的方法