简短版:
我们可以使用以下方式获取 Func<T,T>
的类型:
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>
和 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而是使用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>
只是一个例子,问题不特定于任何类型。