为什么C#小数离不开m后缀进行初始化? [英] Why c# decimals can't be initialized without the M suffix?

查看:393
本文介绍了为什么C#小数离不开m后缀进行初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class MyClass
{
    public const Decimal CONSTANT = 0.50; // ERROR CS0664   
}

产生这个错误:

produces this error:

错误CS0664:double类型的文字不能被隐式转换为   键入十进制;使用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

作为记录。但这部作品:

public class MyClass
{
    public const Decimal CONSTANT = 50; // OK   
}

我不知道他们为什么禁止的第一个。这似乎怪我。

And I wonder why they forbid the first one. It seems weird to me.

推荐答案

的文字的没有的的 M 的后缀是<$ C类型$ C>双 - 这是这么简单。你不能初始化浮动这种方式之一:

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 隐式转换(字面的类型)十进制。有没有从隐式转换双十进制(因为它可能会丢失信息)。

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).

我个人倒有preferred,如果有自己被的没有的默认值或者默认一直十进制,但这一个不同的问题...

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天全站免登陆