不同类型的评估关键字VAR [英] Different types evaluated for keyword var
问题描述
我有以下的code,旨在推断由编译器分配给 VAR
关键字类型2个街区。
I have following 2 blocks of code which aims to infer the type assigned to var
keyword by the compiler.
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 ?
如果变种b
和 VARç
几乎相同initialization-其中 VARç
甚至明确的,那么为什么它会出现意想不到的数据类型System.Int64?
If var b
and var c
have almost same initialization- where var c
is even explicit, then why does it give unexpected data-type System.Int64 ?
推荐答案
由于
变种B = 0x80000000的 - 为0x1;
时,已经计算。通过优化
is already Computed. by Optimizations
但
var val1 = 0x80000000;
var val2 = 0x1;
var c = val1 - val2;
不计算呢。和编译器猜测, 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
是 UInt32的
现在,因为编译器计算它,并知道resault。
c
is UInt32
now because compiler compute it and knows the resault.
由于 VAL1
和 val2的
为常数,编译器知道,他们不会得到改变。所以没有必要的Int64
更多
Because val1
and val2
are constant and Compiler knows that they will not get changed. so there is no need for Int64
any more
这篇关于不同类型的评估关键字VAR的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!