【发布时间】:2014-08-06 06:41:16
【问题描述】:
短版:
我们可以得到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> 的类型,就像我上面失败的尝试一样,然后我可以使用this overload 的GetMethod 而不是使用Linq 并执行以下操作:
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> 只是一个例子,问题不针对任何类型。
【问题讨论】:
-
+1 好问题!当我们需要乔恩·斯基特时,他在哪里?哈哈
标签: c# generics reflection