简洁版本 :
我们可以得到typeofFunc<T,T>
using:
typeof(Func<,>)
但如果我想得到类型怎么办Func<T, bool>
,我应该使用什么,或者可以做什么?显然这不能编译:
typeof(Func<, bool>)
长版:
考虑以下场景,我有两个类似的方法,我想得到第二个(Func<T, int>
)使用反射:
public void Foo<T>(Func<T, bool> func) { }
public void Foo<T>(Func<T, int> func) { }
我正在尝试这个:
var methodFoo = typeof (Program)
.GetMethods()
.FirstOrDefault(m => m.Name == "Foo" &&
m.GetParameters()[0]
.ParameterType
.GetGenericTypeDefinition() == typeof (Func<,>));
但由于泛型类型定义Func<T, bool>
and Func<T, int>
相等它给了我第一种方法。为了解决这个问题,我可以执行以下操作:
var methodFoo = typeof (Program)
.GetMethods()
.FirstOrDefault(m => m.Name == "Foo" &&
m.GetParameters()[0]
.ParameterType
.GetGenericArguments()[1] == typeof(int));
然后我得到了正确的方法,但我不喜欢这种方式。对于更复杂的情况来说,这似乎是一种开销。我想做的是获取类型Func<T,bool>
就像我上面失败的尝试一样,我可以使用而不是使用 Linq这种超载 http://msdn.microsoft.com/en-us/library/5fed8f59(v=vs.110).aspx of GetMethod
并执行如下操作:
var methodFoo = typeof (Program)
.GetMethod("Foo",
BindingFlags.Public | BindingFlags.Instance,
null,
new[] {typeof (Func<, bool>)}, // ERROR typeof(Func<,>) doesn't work either
null);
注:当然可以Func<T,T>
只是一个例子,问题并不特定于任何类型。