为什么 .NET 自然地采用某些类型?
Why does .NET naturally assume certain types?
考虑以下代码:
var x = 32;
数字 32 将适合 sbyte
、byte
、short
、ushort
等
为什么 .NET 假设这是一个 int
?
var x = 3.2;
的相同问题 .NET 假定 double
Why does .NET assume this is an int?
错误question/subject。 C# 编译器假设这是一个 int
.
The type of an integer literal is determined as follows:
If the literal has no suffix, it has the first of these types in which its value can be represented: int, uint, long, ulong.
If no real type suffix is specified, the type of the real literal is double.
编译器的另一个重要“技巧”,使它合法:
byte b = 5;
(通常 5 是 int
,并且没有从 int
到 byte
的隐式转换),但是:
摘自6.1.6 Implicit constant expression conversions:
An implicit constant expression conversion permits the following conversions:
A constant-expression (Section 7.15) of type int can be converted to type sbyte, byte, short, ushort, uint, or ulong, provided the value of the constant-expression is within the range of the destination type.
A constant-expression of type long can be converted to type ulong, provided the value of the constant-expression is not negative.
考虑以下代码:
var x = 32;
数字 32 将适合 sbyte
、byte
、short
、ushort
等
为什么 .NET 假设这是一个 int
?
var x = 3.2;
的相同问题 .NET 假定 double
Why does .NET assume this is an int?
错误question/subject。 C# 编译器假设这是一个 int
.
The type of an integer literal is determined as follows:
If the literal has no suffix, it has the first of these types in which its value can be represented: int, uint, long, ulong.
If no real type suffix is specified, the type of the real literal is double.
编译器的另一个重要“技巧”,使它合法:
byte b = 5;
(通常 5 是 int
,并且没有从 int
到 byte
的隐式转换),但是:
摘自6.1.6 Implicit constant expression conversions:
An implicit constant expression conversion permits the following conversions:
A constant-expression (Section 7.15) of type int can be converted to type sbyte, byte, short, ushort, uint, or ulong, provided the value of the constant-expression is within the range of the destination type.
A constant-expression of type long can be converted to type ulong, provided the value of the constant-expression is not negative.