我从另一个问题(稍作修改)中借用了下面的代码,以在我的代码中使用:
internal class PositiveDouble
{
private double _value;
public PositiveDouble(double val)
{
if (val < 0)
throw new ArgumentOutOfRangeException("Value needs to be positive");
_value = val;
}
// This conversion is safe, we can make it implicit
public static implicit operator double(PositiveDouble d)
{
return d._value;
}
// This conversion is not always safe, so we're supposed to make it explicit
public static explicit operator PositiveDouble(double d)
{
return new PositiveDouble(d); // this constructor might throw exception
}
}
此代码的原作者正确地遵守了 MSDN 的隐式和显式文档中给出的警告,但这是我的问题:在潜在异常代码中是否总是必要的?explicit
所以,我的代码中有一些从 PositiveDouble 派生的类型(例如“Volume”),我希望能够像下面的第一行一样方便地设置实例:
Volume v = 10; //only allowed by implicit conversion
Volume v = new Volume(10) //required by explicit conversion, but gets messy quick
被迫在任何地方使用显式强制转换会使代码的可读性大大降低。它如何保护用户?在我的程序的语义中,我从不期望 Volume 是负数。事实上,如果它发生了,我希望会抛出一个异常。因此,如果我使用隐式转换并抛出异常,什么“意外结果”可能会让我大吃一惊?