针对关键字 var 评估的不同类型

Different types evaluated for keyword var

我有以下 2 个代码块,旨在推断编译器分配给 var 关键字的类型。

var b = 0x80000000 - 0x1;
Console.WriteLine("b: {0}", b);
Console.WriteLine("b.GetType()={0}", b.GetType());

uint val1 = 0x80000000;
int val2 = 0x1;
var c = val1 - val2;
Console.WriteLine("c: {0}", c);
Console.WriteLine("c.GetType(): {0}", c.GetType());

输出:

  b: 2147483647                   //Result of UInt32-Int32
                                  //(as compiler assigns datatype in the
                                  //order of int, uint, long and ulong)
  b.GetType()=System.UInt32       //OK

  c: 2147483647                   //Uint32-Int32                               
  c.GetType(): System.Int64       //Not Understood, why not UInt32 ?

如果 var bvar c 具有几乎相同的初始化 - 其中 var c 甚至是显式的,那么为什么它会给出意外的数据类型 System.Int64 ?

编译器自动将类型扩展为 64 位,因为这是唯一可以保存 UInt32Int32 之间运算结果的整数。尝试更改为

ulong val1 = 0x80000000;
long val2 = 0x1;

你会看到编译错误,因为编译器找不到保存结果的类型。

Int64 不是 b 的推断类型,因为编译器检测到常量属于 Int32 范围。尝试

var b = 0x800000000000 - 0x1;

你会看到推断类型 long

Because

var b = 0x80000000 - 0x1;

is already Computed. by Optimizations

But

var val1 = 0x80000000;
var val2 = 0x1;
var c = val1 - val2;

is Not computed yet. and compiler guess that the val1 and val2 may be changed later...

const uint val1 = 0x80000000;
const int val2 = 0x1;
var c = val1 - val2;

c is UInt32 now because compiler compute it and knows the resault.

Because val1 and val2 are constant and Compiler knows that they will not get changed. so there is no need for Int64 any more

问题是,当您在 intuint 之间进行运算时,uint 被转换为有符号数。

因此,为了 uint 能够将其所有信息(从 0 到 23 - 1)存储在一个无符号数中,它必须是转换为 long(从 -263 到 263 - 1),因为 int 的范围来自-231 到 231 - 1.