为什么c#小数不能在没有M后缀的情况下被初始化? [英] Why c# decimals can't be initialized without the M suffix?

查看:271
本文介绍了为什么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...

这篇关于为什么c#小数不能在没有M后缀的情况下被初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆