如何在转换十进制之前检查有效值

Pos*_*Guy 0 c#

我假设如果total为null,这将会爆炸(我不记得小数是否在开头被初始化为零或零)

public int SomePropertyName
{
    get { return Convert.ToInt32(Decimal.Round(total)); }
}
Run Code Online (Sandbox Code Playgroud)

那么我应该检查null还是> 0?

Jon*_*eet 5

Decimal是一个值类型 - 对于小数,没有"null"这样的值.

但是,十进制的完全可能超出范围int.你可能想要:

decimal rounded = decimal.Round(total);
if (rounded < int.MinValue || rounded > int.MaxValue)
{
    // Do whatever you ought to here (it will depend on your application)
}
return (int) rounded;
Run Code Online (Sandbox Code Playgroud)

Convert.ToInt32考虑到你的财产被宣布为返回,我对你为什么一直在使用感到困惑decimal.这里的大局是什么?你想要实现什么目标?