简体   繁体   中英

Using c#, how can I overload all operators at once?

I have a struct like this.

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

For Money do I have to overload all operators +, -, <, <=, >, >=, ==, !=, etc.? Or is there a way to accept all operators of decimal for Money as well? As you see Money has only one field which is _quantity . I want that all operators asked for Money should return as if it is asked for _quantity.

Maybe overloading below implicit conversion operator will solve the problem.

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

I am creating Money struct, because I do not want to use decimal in my entire project. Compiler should force me to use Money instead of decimal . If I use above conversion operator implicitly, it wil contradict the reason behind creating this struct. Thanks in advance...

You have to implement all the operators separately , but you can simplify the process by inmplementing static Compare method (in order to emulate <=> operator which is not supported by 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);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM