use*_*310 7 c# generics type-constraints
我有一些看起来像这样的代码:
class A<T>
where T : // what should I say here to make this work?
{
void foo()
{
int x = 0;
T y = (T)x; // this is a compile error without proper type restrictions
}
}
Run Code Online (Sandbox Code Playgroud)
目的是使用A类型,如double,float,int.
不,你不能。如果您打算仅对值类型使用此方法,您可以指定一个struct约束,否则您不能限制T为仅 float、int、double。
有一种方法可以消除编译器错误,您可以将值装箱然后将其转换回来,但这不是一个好主意和做法,因为如果 和 的类型x不T兼容,这将失败:
T y = (T)(object)x
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
113 次 |
| 最近记录: |