我有这样的结构。
public struct Money
{
private readonly decimal _quantity;
private Money(decimal qty)
{
_quantity = Math.Round(qty, 2);
}
public static implicit operator Money(decimal dec)
{
return new Money(dec);
}
}
对于Money
我是否必须重载所有运算符+, - ,<,< =,>,> =,==,!=等?或者有没有办法接受decimal
Money
的所有运营商?如您所见Money
只有一个_quantity
字段。我希望所有要求Money
的运营商都应该返回,就像要求_quantity一样。
在隐式转换运算符下面重载可能会解决问题。
public static implicit operator decimal(Money money)
{
return money._quantity;
}
我正在创建Money
struct,因为我不想在整个项目中使用decimal
。编译器应该强制我使用Money
而不是decimal
。如果我隐式使用上面的转换运算符,它将与创建此结构的原因相矛盾。
提前谢谢......
答案 0 :(得分:1)
通过实现static Compare
方法(为了模拟C#)不支持的<=>
运算符
public struct Money: IComparble<Money> {
private readonly decimal _quantity;
...
// C# doesn't have <=> operator, alas...
public static int Compare(Money left, Money right) {
if (left._quantity < right._quantity)
return -1;
else if (left._quantity > right._quantity)
return 1;
else
return 0;
}
public static Boolean operator == (Money left, Money right) {
return Compare(left, right) == 0;
}
public static Boolean operator != (Money left, Money right) {
return Compare(left, right) != 0;
}
public static Boolean operator > (Money left, Money right) {
return Compare(left, right) > 0;
}
public static Boolean operator < (Money left, Money right) {
return Compare(left, right) < 0;
}
public static Boolean operator >= (Money left, Money right) {
return Compare(left, right) >= 0;
}
public static Boolean operator <= (Money left, Money right) {
return Compare(left, right) <= 0;
}
public int CompareTo(Money other) {
return Compare(this, other);
}
}