0

我有一个这样的结构。

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是否必须重载所有运算符 +、-、<、<=、>、>=、==、!= 等?或者有没有办法接受所有的运算decimalMoney?如您所见Money,只有一个字段是_quantity. 我希望所有要求的操作员Money都应该返回,就好像它被要求提供 _quantity 一样。

也许在隐式转换运算符下面重载会解决这个问题。

public static implicit operator decimal(Money money)
{
    return money._quantity;
}

我正在创建Money结构,因为我不想decimal在我的整个项目中使用。编译器应该强制我使用Money而不是decimal. 如果我隐式使用上述转换运算符,它将与创建此结构的原因相矛盾。提前致谢...

4

1 回答 1

1

必须分别实现所有运算符,但您可以通过实现方法来简化过程(以模拟C#不支持的运算符):static Compare<=>

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);
  }
}
于 2014-04-14T07:13:34.367 回答