3

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?

4

7 回答 7

14

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.

于 2012-09-13T23:00:18.300 回答
2

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.

于 2012-09-13T23:14:16.830 回答
1

有默认值,我不能立即告诉你所有这些。类似于如果您调用 5/7 它默认为整数除法。但如果你做 5/7.0 那么它会做常规除法。var 只是将类型设置为分配值的类型,在没有强制转换的情况下,默认情况下它是整数。

于 2012-09-13T23:00:40.270 回答
0

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.

于 2012-09-13T23:00:25.613 回答
0

根据手册

隐式类型的局部变量是强类型的,就像您自己声明了类型一样,但编译器确定类型。

var 关键字指示编译器从初始化语句右侧的表达式推断变量的类型。

简而言之,编译器将检查分配给变量的数据的最低可用类型,并将所述变量强类型化为该数据类型。

于 2012-09-13T23:01:31.093 回答
0

var 关键字自动将给定值设置为编译器可以转换的类型。例如:var s = ""; 包含一个字符串,并将成为一个字符串。

于 2012-09-13T23:01:41.790 回答
-2

它将 a 设置为表达式类型,因为 var 是通用类型,并且由于 CLR 为您处理它需要的内存管理,并将确定表达式的类型并使变量成为该类型。

于 2012-09-13T23:06:24.273 回答