有条件的非此即彼的类型约束 [英] Conditional either-or on type constraint
问题描述
是否有可能有一种类型的约束是或两种类型的,而不是一个和的。一个和是通过将两种类型之间逗号来完成。但对于一个或
Is it possible to have a type constraint that is an "or" of two types instead of an "and". An "and" is accomplished by putting a comma between the two types. But what about an "or"?
class Type1<T, U>
{
public static Type1<T, U> New<V>( V v )
where V : T, U
{
return new Type1<T, U>();
}
}
因此,在上述的例子中,参数传递到新()必须是一个T和一个U.但我想这是不是一件T 或 U形。
推荐答案
有没有办法表达你描述的方式或约束。然而,你可以通过让两个重载其中一个接受 U
和其他效仿这一 T
。那么这两个可以喂到它处理 T
或 U
There is no way to express the "or" constraint in the manner you described. However you can emulate this by having two overloads one which accepts U
and the other T
. These two can then feed into a common function which handles T
or U
class Type1<T, U> {
public static Type1<T, U> New(U p) {
return NewCore(p);
}
public static Type1<T, U> New(T p) {
return NewCore(p);
}
private static Type1<T, U> New(object o) {
...
}
}
不太清楚你想要的 T
或 U
参数做什么,虽然。也许你可以详细一点
Not quite sure what you'd want to do with the T
or U
parameter though. Perhaps you could elaborate a bit
这篇关于有条件的非此即彼的类型约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!