【问题标题】:GetMethod with generic overload [duplicate]具有通用重载的 GetMethod [重复]
【发布时间】:2015-01-26 17:42:50
【问题描述】:

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

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

【问题讨论】:

标签: c# .net generics reflection generic-programming


【解决方案1】:

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

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

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

【讨论】:

  • 那行得通。我想我只需要手动匹配其中的类型。
猜你喜欢
  • 2020-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-26
相关资源
最近更新 更多