gpt4 book ai didi

.net - 网络 5 : Decimal silently truncated - how to make it break?

转载 作者:行者123 更新时间:2023-12-04 07:34:29 25 4
gpt4 key购买 nike

以下是使用 .Net 5 完成的:

编译器不允许以下行,因为数字超过了最大 long 值:

long value = 123456789123456789123456789123456789; // <= Not allowed by compiler

但是,编译器和运行时都允许以下行:

Decimal value = 123456789123456789.123456789123456789m; // No compile time error, no runtime error.

问题是,该值立即被截断为 123456789123456789,12345678912。因此,该值实际上已更改,恕不另行通知。

我想知道在这种情况下是否可以将 dotnet 设置为崩溃,因为我希望事情尽早中断,最好是在编译时或至少在运行时。

有人解决了这个问题吗?

最佳答案

这是设计使然。

From the C# specification:

A real literal suffixed by M or m is of type decimal. For example, the literals 1m, 1.5m, 1e10m, and 123.456M are all of type decimal. This literal is converted to a decimal value by taking the exact value, and, if necessary, rounding to the nearest representable value using banker's rounding. Any scale apparent in the literal is preserved unless the value is rounded or the value is zero (in which latter case the sign and scale will be 0). Hence, the literal 2.900m will be parsed to form the decimal with sign 0, coefficient 2900, and scale 3.

恐怕您唯一的选择是构建一个代码分析器来标记此类行上的错误。

关于.net - 网络 5 : Decimal silently truncated - how to make it break?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67801828/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com