c# - 具有泛型重载的 GetMethod

标签 c# .net generics reflection generic-programming

我有一个包含两个方法的类,用相同的名称和参数重载,但其中一个是通用的:

public class Foo
{
    public string Bar(string s) { throw new NotImplementedException(); }
    public T Bar<T>(string s) { throw new NotImplementedException(); }
}

如何获得 MethodInfo对于这些方法之一?

例如:

var fooType = typeof(Foo);
var methodInfo = fooType.GetMethod("Bar", new[] { typeof(string) }); // <-- [System.Reflection.AmbiguousMatchException: Ambiguous match found.]

.NET Fiddle here

最佳答案

您可以使用 LINQ 来获取通用或非通用的:

fooType.GetMethods().First(m => m.Name == "Bar" && m.IsGenericMethod)

要获得非泛型重载,只需否定 m.IsGenericMethod 的结果即可。

关于c# - 具有泛型重载的 GetMethod,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28155648/

相关文章:

java - 自引用泛型并取回您自己的实例

swift - 如何在类型化为协议(protocol)的 Swift 通用数据结构中使用弱引用?

c# - SFML.Net 无法在 Linux 上找到 native 库

c# - 有没有办法在 Unity 的控制台中使用超链接?

c# - 无法在 Firefox 中读取 ashx 中的 session 变量值?

c# - Entity Framework 查询中的用户 trimstart

.net - 为什么我的 MEF 部分对插件主机不可见?

java - 无法使用通配符泛型类型向 Java 集合添加值

c# - 服务器和客户端之间以两种方式进行进程间通信的最佳方式

c# - NHibernate 批量插入或更新