寻找有关C#中的无限/无限的建议。
我目前正在建立Geometry类,用于诸如Rectangle / Circle等形状。 用户将分别提供宽度/深度和直径的输入。
These properties will be double
and I understand that instead of explicitly overflowing, if you were to multiple double.MaxValue
by 2, then you would get +infinity etc.
每个形状类别将具有其他属性,例如面积,周长等。 因此,即使提供的尺寸小于MaxValue,如果用户如此倾向于,则计算出的值也可能是巨大的数字:
E.g. Math.PI x Math.Pow(diameter, 2) / 4
=> Math.PI x Math.Pow(double.MaxValue, 2) / 4
(即,即使用户提供了MaxValue作为输入,此方法也会导致+ infinity。)
我的问题是我是否应该一直提防无限大? 如果用户值或计算值输入无穷大,是否应该抛出异常(OverflowException)?
似乎检查这些几何类中每个属性/方法的无穷大可能是一种代码味道。 有没有更好的办法?
public double Area
{
get
{
double value = Math.PI * Math.Pow(this.diameter, 2) / 4;
if (double.IsInfinity(value)
{
throw new OverflowException("Area has overflowed.");
}
}
}
public double Perimeter
{
get
{
double value = Math.PI * this.diameter;
if (double.IsInfinity(value)
{
throw new OverflowException("Perimeter has overflowed.");
}
}
}
感谢您的时间和想法! 干杯。