c# - Decimal.Round() 如何抛出 OverflowException

标签 c# decimal coreclr overflowexception

我在用

Decimal.Round(decimal d)

MSDN 说它可以抛出 OverflowException https://msdn.microsoft.com/en-us/library/k4e2bye2(v=vs.110).aspx

我不确定这是怎么发生的。我尝试使用 ilSpy 查看实现 并得到直到外部实现:

// decimal
[SecurityCritical]
[MethodImpl(MethodImplOptions.InternalCall)]
private static extern void FCallRound(ref decimal d, int decimals);

有人知道什么输入可以抛出这个异常吗?

最佳答案

当我们从您已经发现的内容进一步深入时,我们最终会执行 VarDecRound功能。该函数只有一个分支,它返回一个错误代码,即当它的第二个参数 cDecimals 小于零时。此参数表示要四舍五入的小数位数:

if (cDecimals < 0) 
    return E_INVALIDARG; 

(这种断言等同于 .NET 中的 ArgumentException)

正如 James Thorpe 在对 OP 的评论中指出的那样,类似的断言在调用链的更上方完成,here :

if (decimals < 0 || decimals > 28) 
    FCThrowArgumentOutOfRangeVoid(...)

结论:
执行无法到达 the point这将导致抛出 OverflowException,如记录的那样:

  1. OverflowException 似乎已在内部用作一种包罗万象的机制,很像 GDI+ 中的 OutOfMemoryException
  2. 文档与实际实现不符
  3. OverflowException 在概念上什至没有意义。 在相同数据类型中向上或向下舍入值不可能超过 integral min or max range , 因为候选值本身必须在范围内 ( rounding method used )

关于c# - Decimal.Round() 如何抛出 OverflowException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42348680/

相关文章:

c# - 当 native 进程托管 .NET Core 运行时时,在 C# 和 C++ 之间传递 C# 托管实例

asp.net-core - 为什么 ASP.NET Core 将声明两次添加到 User.Claims 属性中?

asp.net-core - dnxcore50 与 dnx451 的性能比较? (CoreClr 与 .net 框架)

c# - 从字符串中分离值

c# - Entity Framework DbContext : Value cannot be null, 参数名称来源

java - 小数格式舍入

MySQL 防止小数字段四舍五入

C# XML 数据反序列化 - 基于引用 ID 应用对象关系

c# - 在 Netduino 板上使用 .NET Micro Framework 提高时间分辨率(用于调暗 LED)?

swift - 字符串转十进制swift