GetMethod 重载 returns 空

GetMethod overload returns null

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

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.