M 后缀与十进制文字的相关性是什么

Sum*_*ith 4 c# decimal literals

decimal l = 50.0M;
Run Code Online (Sandbox Code Playgroud)

我已经看到其他答案表明 M 是明确地将类型声明为十进制 - M 在 C# 十进制文字表示法中代表什么?

然而,当变量的类型被专门说明时,为什么要有个后缀呢?当未指定变量类型时,我可以看到后缀的相关性,例如:

var l = 50.0M
Run Code Online (Sandbox Code Playgroud)

das*_*ght 5

当变量的类型被专门说明时,为什么要有个后缀?

仅在您分配的值具有小数点的情况下才需要强制转换。在您的情况下,50.0表示类型的文字double。您可以通过添加演员来避免后缀,就像这样

decimal l = (decimal)50.0; // Do not do this!
Run Code Online (Sandbox Code Playgroud)

但这可能会导致转换错误:

decimal d = (decimal)1.23456789123456789;
Console.WriteLine(d); // Prints 1.23456789123457
decimal e = 1.23456789123456789M;
Console.WriteLine(e); // Prints 1.23456789123456789
Run Code Online (Sandbox Code Playgroud)

请注意,以下将编译没有后缀或投,因为intdecimal转换从来没有失去精度:

decimal l = 50;
Run Code Online (Sandbox Code Playgroud)

您可能需要M后缀的另一个地方是在操作小数的表达式中:

decimal tenPercentBroken  = myDecimal * 0.1;  // Does not compile
decimal tenPercentCorrect = myDecimal * 0.1M; // Compiles fine
Run Code Online (Sandbox Code Playgroud)


Pat*_*man 1

50.0在 C# 中是一个字面量double,因此如果没有M后缀,您将尝试将 a 隐式转换double为 a decimal(不存在的隐式转换)。

使用decimal l = 50.0M;表示:将此小数分配给该小数变量。