Reputation: 10015
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?
Upvotes: 1
Views: 268
Reputation: 151588
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.
Upvotes: 4