2012-08-09 50 views
2

當我運行:如何爲重載的靜態方法獲取MethodInfo?

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

我得到:

System.Reflection.AmbiguousMatchException: Ambiguous match found. 

這是在努力做到這一點genericly(而不是知道它是一個字符串)

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

編輯 :附加信息:

run寧:

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])} 
+0

如果您使用typeof(Expression).GetMethods,而不是找到多個,它們又有什麼不同? – 2012-08-09 22:29:10

+0

我得到了什麼相當於MSDN文檔中的方法列表。唯一有跡象的是該方法的通用和非通用版本。但是當我使用MakeGenericType()時,我沒有得到靜態方法,這正是我所需要的。 – Charlie 2012-08-10 02:29:49

+1

[Select Right Generic Method with Reflection]的可能重複(http://stackoverflow.com/questions/3631547/select-right-generic-method-with-reflection) – nawfal 2014-01-18 05:48:51

回答

2

不幸的是反射寫作了之前仿製藥可用,經常在所有不支持泛型方法/班好。

類似的問題,這已被要求(GetMethod for generic method)其中的答案已經獲得候選方法和接你的方法收集想要的。