gpt4 book ai didi

c# - var 如何处理数字?

转载 作者:太空狗 更新时间:2023-10-29 21:48:35 24 4
gpt4 key购买 nike

我今天试验了编译器如何确定声明为 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 类型。

关于c# - var 如何处理数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50447239/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com