假设我们有以下类型:
struct MyNullable<T> where T : struct
{
T Value;
public bool HasValue;
public MyNullable(T value)
{
this.Value = value;
this.HasValue = true;
}
public static implicit operator T(MyNullable<T> value)
{
return value.HasValue ? value.Value : default(T);
}
}
并尝试编译以下代码片段:
MyNullable<int> i1 = new MyNullable<int>(1);
MyNullable<int> i2 = new MyNullable<int>(2);
int i = i1 + i2;
这剪辑编译得很好,没有错误。i1 和 i2 转换为整数并评估加法。
但是如果我们有以下类型:
struct Money
{
double Amount;
CurrencyCodes Currency; /*enum CurrencyCode { ... } */
public Money(double amount, CurrencyCodes currency)
{
Amount = amount;
Currency = currency;
}
public static Money operator + (Money x, Money y)
{
if (x.Currency != y.Currency)
// Suppose we implemented method ConvertTo
y = y.ConvertTo(x.Currency);
return new Money(x.Amount + y.Amount, x.Currency);
}
}
尝试编译另一个代码片段:
MyNullable<Money> m1 =
new MyNullable<Money>(new Money(10, CurrenciesCode.USD));
MyNullable<Money> m2 =
new MyNullable<Money>(new Money(20, CurrenciesCode.USD));
Money m3 = m1 + m2;
现在的问题是,为什么编译器会生成“错误 CS0019:运算符 '+' 不能应用于 'MyNullable<Money>' 和 'MyNullable<Money>' 类型的操作数”?