具有泛型重载的 GetMethod

Ban*_*San 2 .net c# generics reflection generic-programming

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

public class Foo
{
    public string Bar(string s) { throw new NotImplementedException(); }
    public T Bar<T>(string s) { throw new NotImplementedException(); }
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能获得MethodInfo这些方法之一?

例如:

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

.NET 小提琴在这里

Sel*_*enç 5

您可以使用 LINQ 来获取泛型或非泛型:

fooType.GetMethods().First(m => m.Name == "Bar" && m.IsGenericMethod)
Run Code Online (Sandbox Code Playgroud)

要获得非通用重载,只需否定m.IsGenericMethod.