1

I want to get a method from specific interface, but it can be in multiple interfaces. I write this code:

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.

So I expect that it will search method through IComparable<T>, and, if didn't found, will search it in non-generic IComparable. But it doesn't. Well, now I rewrite it:

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) });
    ...

And now it works.

Why first option is not working?

Alex Zhukovskiy
  • 9,565
  • 11
  • 75
  • 151

1 Answers1

4

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

No, it looks for a method with the signature CompareTo(IComparable<TProperty>, IComparable).

This is also in the Type.GetMethod() documentation:

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

Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • Okay, thanks for reply. But then, what method can satisfy my needs? This way looks ugly – Alex Zhukovskiy Apr 30 '15 at 10:00
  • Not sure what your needs are. See [How to get MethodInfo of interface method, having implementing MethodInfo of class method?](http://stackoverflow.com/questions/1113635/how-to-get-methodinfo-of-interface-method-having-implementing-methodinfo-of-cla). – CodeCaster Apr 30 '15 at 10:03
  • I want to get a method from non-generic interface only if it doesn't exist in generic. The only way I found is just call GetMethod twice, but it's ugly beacause of copy-paste and performance reasons. – Alex Zhukovskiy Apr 30 '15 at 10:06