我在用
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
,如记录的那样:
- OverflowException 似乎已在内部用作一种包罗万象的机制,很像 GDI+ 中的 OutOfMemoryException
- 文档与实际实现不符
- OverflowException 在概念上什至没有意义。 在相同数据类型中向上或向下舍入值不可能超过 integral min or max range , 因为候选值本身必须在范围内 ( rounding method used )
关于c# - Decimal.Round() 如何抛出 OverflowException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42348680/