我想从特定接口(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/