为什么c#小数不能在没有M后缀的情况下被初始化?
public class MyClass
{
public const Decimal CONSTANT = 0.50; // ERROR CS0664
}
产生此错误:
错误CS0664:double类型的文字不能隐式转换为
类型'decimal';使用'M'后缀创建此类型的文字
error CS0664: Literal of type double cannot be implicitly converted to type 'decimal'; use an 'M' suffix to create a literal of this type
as 记录的。但是这样做有效:
as documented. But this works:
public class MyClass
{
public const Decimal CONSTANT = 50; // OK
}
我不知道为什么他们禁止第一个。对我而言似乎很奇怪。
And I wonder why they forbid the first one. It seems weird to me.
没有的文字的类型 m
后缀是 double
- 这很简单。您不能以以下方式初始化 float
:
The type of a literal without the m
suffix is double
- it's as simple as that. You can't initialize a float
that way either:
float x = 10.0; // Fail
文字的类型应从文字本身清楚,它被分配给的变量应该可以从分配给该文字的类型。所以你的第二个例子是有效的,因为有一个从 int
(文字的类型)到 decimal
的隐式转换。没有从 double
到 decimal
(因为它可能丢失信息)的隐式转换。
The type of the literal should be made clear from the literal itself, and the type of variable it's assigned to should be assignable to from the type of that literal. So your second example works because there's an implicit conversion from int
(the type of the literal) to decimal
. There's no implicit conversion from double
to decimal
(as it can lose information).
个人而言,如果默认为否,或者默认值为 decimal
,则我会偏好这是一个不同的事情...
Personally I'd have preferred it if there'd been no default or if the default had been decimal
, but that's a different matter...