c# - GetMethod 重载返回 null

标签 c# .net generics reflection

我想从特定接口(interface)获取一个方法,但它可以在多个接口(interface)中。我写这段代码:

private static Expression<Func<T, T, int>> CreateCompareTo<TProperty>(MemberExpression expression, Expression<Func<T, T, int>> result) where TProperty : IComparable<TProperty>, IComparable
{
    var methodInfo = typeof(TProperty).GetMethod("CompareTo", new[] { typeof(IComparable<TProperty>), typeof(IComparable) });
    ...

MSDN

An array of Type objects representing the number, order, and type of the parameters for the method to get.

所以我希望它会通过 IComparable<T> 搜索方法, 如果没有找到,将在非通用 IComparable 中搜索它.但事实并非如此。好吧,现在我重写它:

private static Expression<Func<T, T, int>> CreateCompareTo<TProperty>(MemberExpression expression, Expression<Func<T, T, int>> result) where TProperty : IComparable<TProperty>, IComparable
{
    Type t = typeof(TProperty);
    var methodInfo = t.GetMethod("CompareTo", new[] { typeof(IComparable<TProperty>) }) ?? t.GetMethod("CompareTo", new[] { typeof(IComparable) });
    ...

现在可以了。

为什么第一个选项不起作用?

最佳答案

GetMethod("CompareTo", new[] { typeof(IComparable<TProperty>), typeof(IComparable)})

So I expect that it will search method through IComparable, and, if didn't found, will search it in non-generic IComparable

不,它寻找一个带有签名的方法 CompareTo(IComparable<TProperty>, IComparable) .

这也在 Type.GetMethod() documentation中:

Searches for the specified public method whose parameters match the specified argument types.

关于c# - GetMethod 重载返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29964586/

相关文章:

c# - 使用 Roslyn 引用 PCL 库会导致 .NET 版本问题

c# - 通用类型的集合

ios - 通用类型编译器错误的 Swift 扩展

java - 仅适用于特定类型的通用类

c# - ASP.NET MVC 在方法而不是参数上绑定(bind)属性

C# 赢。表格 - 如何从 "System Summary"获取 "msinfo32"

c# - 使用 IIS 和 ASP.NET 跟踪文件访问

c# - c#中不知道key的情况下读取json

c# - 使用 linq to sql 回滚?

c# - 如何将基于 'using' 的 GC 生命周期打开为基于 'create-dispose' 的生命周期?