本文介绍了有没有办法让typeof运算函数功能< T,BOOL&GT ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

短版:



我们可以得到的typeof Func键< T,T> 使用:

 的typeof(Func键<,>)

但如果我想获得 Func键< T,BOOL> ,我应该怎么用,或者是有可能这样做?显然,这不能编译:

 的typeof(Func键< ;,布尔>)






龙版本:



考虑以下情形,我有两个类似的方法,我想获得第二个( Func键< T,INT> )使用反射:

 公共无效美孚< T>(Func键< T,BOOL> FUNC){} 

公共无效美孚< T> (Func键< T,INT> FUNC){}

我想这样的:

  VAR methodFoo = typeof运算(程序)
.GetMethods()
.FirstOrDefault(M = GT; m.Name ==富与功放;&安培;
m.GetParameters()[0]
.ParameterType
.GetGenericTypeDefinition()== typeof运算(Func键<,>));



不过,由于 Func键1所述的泛型类型定义; T,BOOL> Func键< T,INT> 等于它给我的第一个方法。为了解决这个问题,我可以做到以下几点:

  VAR methodFoo = typeof运算(程序)
.GetMethods()
.FirstOrDefault(M = GT; m.Name ==富与功放;&安培;
m.GetParameters()[0]
.ParameterType
.GetGenericArguments()[1] == typeof运算(INT));



然后我得到了正确的方法,但我不喜欢这种方式。而现在似乎为更复杂的情况下,一个开销。我想要做的就是的类型Func键< T,BOOL> 就像在我失败的尝试上面的话,而不是使用LINQ我可以使用的>和做类似如下:

  VAR methodFoo = typeof运算(程序)
.GetMethod(富,
BindingFlags.Public | BindingFlags.Instance,
空,
新的[] {typeof运算(Func键< ;,布尔>)} //错误的typeof(Func键<,>)无法正常工作或
NULL);

请注意:Ofcourse Func键< T,T> 只是一个例子,问题是不特定于任何类型的。


解决方案

不幸的是,你不能建立一个的System.Type 对象部分的约束泛型类型。你做的方式(即 GetGenericArguments()[1] == typeof运算(INT))是这样做的正确方法。



如果您需要重新使用在多个地方,你可以建立,需要一个泛型类型定义和数组的帮助扩展方法的System.Type 对象,并返回真正如果有匹配的:

 静态布尔IsGenericInstance(这种类型T,类型genTypeDef,则params类型[]参数){
如果返回false(t.IsGenericType!);
如果(t.GetGenericTypeDefinition()= genTypeDef!)返回false;
VAR typeArgs = t.GetGenericArguments();
如果(!typeArgs.Length = args.Length)返回false;
//穿过的参数去,空解释为任何类型的
的for(int i = 0; i = args.Length;!我++){
如果(参数[我] == NULL)继续;
如果(参数[I] = typeArgs [I]!)返回false;
}
返回真;
}

现在你可以重写你这样的代码:

  VAR methodFoo = typeof运算(程序)
.GetMethods()
.FirstOrDefault(M = GT; m.Name ==富&放大器;&安培;
m.GetParameters()[0]
.ParameterType
.IsGenericInstance(typeof运算(Func键<,>),空的typeof(布尔))
);



The type T above is the generic type parameter of your generic method Foo. Since it is not "any type", you could construct this type if you wish:

var typeT = methodFoo.GetGenericArguments()[0];
var funcTbool = typeof(Func<,>).MakeGenericType(typeT, typeof(bool));

The catch is that typeT is bound to the specific generic method, making the funcTbool type not suitable for searching across multiple independent generic methods.

If T were a type argument of the class to which the method belongs, say

class FooType<T> {
    public void Foo(Func<T, bool> func) { }
    public void Foo(Func<T, int> func) { }
}

you would be able to construct a funcTbool based on FooType<>'s generic type parameter, and search for it in the signatures of the different Foo(...) methods.

这篇关于有没有办法让typeof运算函数功能&LT; T,BOOL&GT ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 22:38
查看更多