本文介绍了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的通用方法
发布评论