Why var a = 7;
would set a
type to a certain type (i.e. int
instead of byte
)? Are there any rules/defaults/checks made on the fly by C# compiler?
7 回答
It's not clear what you mean by "on the fly" - but the C# compiler simply follows the rules laid down in the spec. For a declaration of the kind:
var a = expression;
the type of a
is the type of expression
. The expression 7
is of type int
, although it's also known to be a constant within the range of byte
, allowing:
byte a = 7;
to compile. The availability of that conversion to byte
doesn't change the type of the expression 7
though, so int
is what the C# compiler uses for the type of a
.
Note that I'd recommend against using var
for constants like this. It ends up with code which can get pretty confusing around the boundaries of int
, uint
, long
etc. var
is meant to help with anonymous types, and also to help make code more readable. When it makes code less readable, just don't use it.
The compiler treats any integer literal in your code, that does not have a suffix, as an int
.
So this:
byte myByte = 255;
..is actually implicitly converting the int
constant 255, to a byte.
That is why var
is infered to be an integer.. because the compiler uses integer literals by default.
If you were to do this:
var a = 7L;
A would be of type long
.
有默认值,我不能立即告诉你所有这些。类似于如果您调用 5/7 它默认为整数除法。但如果你做 5/7.0 那么它会做常规除法。var 只是将类型设置为分配值的类型,在没有强制转换的情况下,默认情况下它是整数。
var
does not mean "determine the type at runtime", it means "determine the type using the result type of the expression on the right hand side of the assignment operator." It is determined at compile time.
var 关键字自动将给定值设置为编译器可以转换的类型。例如:var s = ""; 包含一个字符串,并将成为一个字符串。
它将 a 设置为表达式类型,因为 var 是通用类型,并且由于 CLR 为您处理它需要的内存管理,并将确定表达式的类型并使变量成为该类型。