【发布时间】:2015-04-30 18:01:31
【问题描述】:
我想从特定接口获取方法,但它可以在多个接口中。我写了这段代码:
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
一个 Type 对象数组,表示数量、顺序和类型 要获取的方法的参数。
所以我希望它会通过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) });
...
现在它可以工作了。
为什么第一个选项不起作用?
【问题讨论】:
标签: c# .net generics reflection