var 如何处理数字?

How does var work for numbers?

我今天试验了编译器如何确定声明为 var 的数字的类型。

var a = 255; //Type = int. Value = byte.MaxValue. Why isn't this byte?
var b = 32767; //Type = int. Value = short.MaxValue. Why isn't this short?
var c = 2147483647; //Type = int. Value = int.MaxValue. int as expected.
var d = 2147483648; //Type = uint. Value = int.MaxValue + 1. uint is fine but could have been long?
var e = 4294967296; //Type = long. Value = uint.MaxValue + 1. Type is long as expected.

为什么 intInt32.MinValueInt32.MaxValue 之间的任何数字的默认值?

使用尽可能小的数据类型来节省内存不是更好吗? (我知道现在内存很便宜,但是,节省内存并不是那么糟糕,特别是如果它很容易做到的话)。

如果编译器确实使用了最小的数据类型,并且如果您有一个 255 的变量并且知道稍后您想要存储一个像 300 这样的值,那么程序员可以直接声明它 short而不是使用 var.

为什么 var d = 2147483648 隐含地 uint 而不是 long

似乎编译器总是会尽可能尝试使用 32 位整数,首先是有符号的,然后是无符号的,然后是 long

Seems as though the compiler will always try and use a 32 bit integer if it can, first signed, then unsigned, then long.

完全正确。 C# Language Specification 解释说它试图选择一个整数类型,该类型使用尽可能少的字节数来表示没有后缀的整数文字。以下是语言规范的解释:

To permit the smallest possible int and long values to be written as decimal integer literals, the following two rules exist:

  • When a decimal-integer-literal with the value 2147483648 and no integer-type-suffix appears as the token immediately following a unary minus operator token, the result is a constant of type int with the value −2147483648. In all other situations, such a decimal-integer-literal is of type uint.
  • When a decimal-integer-literal with the value 9223372036854775808 and no integer-type-suffix or the integer-type-suffix L or l appears as the token immediately following a unary minus operator token, the result is a constant of type long with the value −9223372036854775808. In all other situations, such a decimal-integer-literal is of type ulong.

请注意,语言规范明确提到了您的 var d = ... 示例,要求结果的类型为 uint