C# 检查计算是否超过MaxValue
我目前得到了以下方法,它返回给我百分比值。例如,对于$350000的项目价格和7%的百分比,它返回24500C# 检查计算是否超过MaxValue,c#,overflow,decimal,C#,Overflow,Decimal,我目前得到了以下方法,它返回给我百分比值。例如,对于$350000的项目价格和7%的百分比,它返回24500 public static decimal GetPercentValue(decimal? percentage, decimal baseValue) { decimal result = 0m; if (percentage != null) { try {
public static decimal GetPercentValue(decimal? percentage, decimal baseValue)
{
decimal result = 0m;
if (percentage != null)
{
try
{
result = Convert.ToDecimal(baseValue * percentage / 100m);
}
catch (OverflowException)
{
result = 0;
Logger.Warn("OverflowException caught in GetPercentValue() - should better be handled UI-Sided!");
}
}
return result;
}
我不认为这是正确的处理方式,所以有没有办法避免在这种情况下出现异常
当用户输入一个疯狂的数字,如9999999999999999999
并计算其99999999999%
时,将抛出OverflowException。这样,我就无法检查百分比
或基值
,因为错误处理应该(很可能)在方法之外进行。现在,您正在隐藏异常并返回错误的结果(发生错误时返回0)。方法的调用方无法判断结果是否正确,或者是否是由于OverflowException造成的
我会像这样重写这个方法:
public static decimal GetPercentValue(decimal? percentage, decimal baseValue)
{
if (percentage == null)
return 0;
return baseValue*(percentage.Value/100);
}
还可以选择添加一个验证方法,用户可以在调用real方法之前调用该方法来检查参数。。验证错误可能会显示在UI中:
public static string ValidatePercentValue(decimal? percentage, decimal baseValue)
{
try
{
GetPercentValue(percentage, baseValue);
return null;
}
catch (Exception ex)
{
return ex.Message;
}
}
除此之外,注意到
baseValue*(percentage.Value/100)
。。。比…好
baseValue*percentage.Value/100
尝试计算decimal.MaxValue的100%。第一个有效,而第二个抛出OverflowException。这是一个老问题,但我遇到了一个类似的问题,并考虑提供一个可能的替代解决方案。当两个数字的计算产生一个大于MaxValue的数字时,就会出现问题。这会导致异常,并且很难以通常的方式进行测试:
decimal existingValue = decimal.MaxValue;
decimal newValue = (decimal)100;
//doesn't work -- exception thrown here
if(existingValue + newValue <= decimal.MaxValue)
{
}
由于减法运算,未超过MaxValue。我还没有试过乘法/除法的例子,但我猜它也会起作用。我认为这不是正确的处理方法
-你是什么意思?现在还不清楚你认为正确的方法应该是什么样子。如果你超过了最大值,即79228162514264337593543950335,也许你想重新考虑你的方法?@Oded我认为这应该(或可能)是可能的,而不需要通过一个简单的If-statement来承担溢出异常的沉重成本。这可能不是问题。如果您仅在异常情况下获得异常(例如真实用户不会输入期望正常结果的疯狂数量),那么实际上没有开销。不要指望解决你没有的问题。如果您已经将此函数识别为瓶颈(在分析之后),那么当然可以修复它,但不能在之前修复。我想您是对的。在执行异常操作时,应抛出异常。这将使用户重新考虑他们的操作…:)
if(decimal.MaxValue - existingValue >= newValue)
{
//DoSomething
}