Why does this implicit conversion from int to uint work?

后端 未结 3 1358
再見小時候
再見小時候 2020-12-17 17:25

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

That demonstrates an interesting case. \"uint x = (int)0;\" w

3条回答
  •  无人及你
    2020-12-17 17:31

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

    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
    

提交回复
热议问题