为什么这个从int隐式转换为uint工作?转换为、隐式、工作、int

2023-09-03 00:23:37 作者:阁下久等了

使用铸造空不编译为灵感,并从埃里克利珀的评论:

Using Casting null doesn't compile as inspiration, and from Eric Lippert's comment:

这说明了一个有趣的案例。 UINT X =(INT)0;将会   即使int是不能隐式转换为uint成功。

That demonstrates an interesting case. "uint x = (int)0;" would succeed even though int is not implicitly convertible to uint.

我们知道这是不行的,因为对象不能分配给字符串

We know this doesn't work, because object can't be assigned to string:

string x = (object)null;

但这个呢,虽然直观上它不应该:

But this does, although intuitively it shouldn't:

uint x = (int)0;

为什么确实编译器允许这种情况下,当 INT 不隐式转换为 UINT

Why does the compiler allow this case, when int isn't implicitly convertible to uint?

推荐答案

整型常量转换视为由C#语言很特别的;这里的规范的第6.1.9:

Integer constant conversions are treated as very special by the C# language; here's section 6.1.9 of the specification:

int类型的常量前pression可转换为类型为sbyte,字节,短,USHORT,uint或ulong,则提供了恒定的前pression的值在目标范围内类型。长型的常量EX pression可以转换为ulong类型,所提供的不断前pression值不为负。

A constant expression of type int can be converted to type sbyte, byte, short, ushort, uint, or ulong, provided the value of the constant-expression is within the range of the destination type. A constant expression of type long can be converted to type ulong, provided the value of the constant expression is not negative.

这允许你做这样的事情:

This permits you to do things like:

byte x = 64;

这将原本需要一个丑陋的显式转换:

which would otherwise require an ugly explicit conversion:

byte x = (byte)64; // gross