T是type1或type2的通用方法 [英] Generic method where T is type1 or type2
本文介绍了T是type1或type2的通用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有一种方法可以声明泛型类型为type1 或 type2的泛型函数?
Is there a way to declare a generic function that the generic type is of type1 or type2?
示例:
public void Foo<T>(T number)
{
}
我可以约束T为整型还是整型
Can I constraint T to be int or long
推荐答案
尽管您可以使用通用约束来限制类型不幸的是,对于每个泛型参数T,都没有一个可以让您在编译时强制执行T是 type1还是type2
。
Although you could use a generic constraint to limit the type of each generic argument T, unfortunately there is none that would allow you to enforce at compile time whether T is type1 or type2
.
在编译时也没有任何方法可以强制您的泛型参数只能是任何原始类型(int,long,double,...)。
Nor is there any way to enforce at compile time that your generic argument can only be of any primitive type (int, long, double, ...).
这篇关于T是type1或type2的通用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文