使用c#,如何一次性重载所有运算符?

时间:2014-04-14 07:02:13

标签: c# operator-overloading conversion-operator

我有这样的结构。

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。如果我隐式使用上面的转换运算符,它将与创建此结构的原因相矛盾。 提前谢谢......

1 个答案:

答案 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);
  }
}