我刚刚发现这个:
ushort i = 4;
i = i + 4;
给出编译器错误:
无法将类型“int”隐式转换为“ushort”。存在显式转换(您是否缺少演员表?)
我必须这样修复它:
ushort i = 4;
i = (ushort)(i + 4);
这背后的原因是什么?使用所有数据类型不应该是显而易见且易于使用的吗?
文字4
是 an int
,加法i + 4
也是,被提升为。此加法的结果也是,因此您不能在没有强制转换的情况下将其分配给 a ,因为 C# 不允许隐式转换为更小的数值类型。int
i
int
int
ushort
原因是因为 ushort + ushort 实际上返回一个 int。查看此线程以获取有关为什么会这样的更多详细信息。
这是因为编译器将其4
视为integer
. 从较高数据类型到较低数据类型的转换需要显式转换。
根据 C# 语言标准,特别是关于整数文字的第 2.4.4.2 节:
整数文字的类型确定如下:
如果字面量没有后缀,则它具有可以表示其值的第一种类型:int、uint、long、ulong。如果文字以 U 或 u 为后缀,则它具有可以表示其值的第一种类型:uint、ulong。如果文字以 L 或 l 为后缀,则它具有可以表示其值的第一种类型:long、ulong。如果文字以 UL、Ul、uL、ul、LU、Lu、lU 或 lu 为后缀,则为 ulong 类型。
因此,您的号码被视为 int,这就是原因。
The +
-operatior for integer types is defined only between pairs of int
, uint
, long
, and ulong
. To calculate i+4
first i
has to be converted from ushort
through an implicit numeric conversion into int
, and the result is of the same type - also int
So the type of i+4
is actually int
. Since there is no implicit conversion that would allow assigning an int
to a variable defined as ushort
the compiler gives you an error for i = i + 4
.
Note that you still can use the below because +=
involves an implicit cast:
i += 4;
I think the main thing to take away from the comments is that int32 was just the 'default' type to be used by the common architecture back in the day. I don't know about native support for smaller integer types by current processors, but I wouldn't be surprised if everything is still converted to int32 by the compiler under water even if it is a ushort.
So (u)short is more like a validation constraint for the programmer than a memory-saver. Even if it is a memory saver, I wouldn't be surprised if more CPU cycles are needed to convert back and to ushorts.