可以将一个特定的"从int转换"作为C#中的类型约束吗?

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.

Sel*_*enç 1

不,你不能。如果您打算仅对值类型使用此方法,您可以指定一个struct约束,否则您不能限制T为仅 float、int、double。

有一种方法可以消除编译器错误,您可以将值装箱然后将其转换回来,但这不是一个好主意和做法,因为如果 和 的类型xT兼容,这将失败:

T y = (T)(object)x
Run Code Online (Sandbox Code Playgroud)

  • 但是,您无法将 float 拆箱为 int。 (2认同)