【问题标题】:How do I get a MethodInfo for an overloaded static method?如何获取重载静态方法的 MethodInfo?
【发布时间】:2012-08-09 22:14:40
【问题描述】:

当我跑步时:

MethodInfo m = typeof(Expression).GetMethod("Lambda", new Type[]{typeof(Expression), typeof(ParameterExpression[])});

我明白了:

System.Reflection.AmbiguousMatchException: Ambiguous match found.

这是为了一般地做到这一点(而不是知道它是一个字符串)

var newExpression = Expression.Lambda<Func<T, string>>(propertyExpression, parameters);
return entities.OrderBy(newExpression);

编辑:附加信息:

运行:

typeof(Expression).GetType().GetMethod("GetMethodCandidates", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(typeof(Expression),new object[]{"Lambda", BindingFlags.Static| BindingFlags.Public, CallingConventions.Standard,new Type[]{typeof(Expression), typeof(ParameterExpression).MakeArrayType()},false})

返回数组:

[0]: {System.Linq.Expressions.Expression`1[TDelegate] Lambda[TDelegate](System.Linq.Expressions.Expression, System.Linq.Expressions.ParameterExpression[])}
[1]: {System.Linq.Expressions.Expression`1[TDelegate] Lambda[TDelegate](System.Linq.Expressions.Expression, System.Collections.Generic.IEnumerable`1[System.Linq.Expressions.ParameterExpression])}
[2]: {System.Linq.Expressions.LambdaExpression Lambda(System.Linq.Expressions.Expression, System.Linq.Expressions.ParameterExpression[])}
[3]: {System.Linq.Expressions.LambdaExpression Lambda(System.Linq.Expressions.Expression, System.Collections.Generic.IEnumerable`1[System.Linq.Expressions.ParameterExpression])}

【问题讨论】:

  • 如果你使用 typeof(Expression).GetMethods ,它会发现不止一个,它们有何不同?
  • 我得到了 MSDN 文档中的方法列表。唯一有任何迹象的是该方法的通用和非通用版本。但是当我使用 MakeGenericType() 时,我没有得到静态方法,这是我需要的。

标签: c#-4.0 generics reflection


【解决方案1】:

不幸的是,反射是在泛型可用之前编写的,并且通常根本不能很好地支持泛型方法/类。

已经提出了与此类似的问题 (GetMethod for generic method),答案是获取候选方法并从方法集合中选择您想要的方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-19
    • 1970-01-01
    相关资源
    最近更新 更多