試煉27 - 自訂 class 技巧3 怎麼算加減乘除

2022 鐵人賽文 搬回點部落

開始試煉

自訂class 怎麼算加減乘除
首先 先來自訂class

void Main()
{
    var gil1 = new Gil(50);
    var gil2 = new Gil(25);
    (gil1 + gil2).ToString().Dump("gil1 + gil2");
    (gil1 - gil2).ToString().Dump("gil1 - gil2");
    (gil1 * gil2).ToString().Dump("gil1 * gil2");
    (gil1 / gil2).ToString().Dump("gil1 / gil2");
}
public class Gil
{
    public int Amount { get; set; }
    public string CurrencyName { get; } = "GD";
    public Gil(int amount)
    {
        Amount = amount;
    }
    public override string ToString() => $"{Amount} {CurrencyName}";
}

IDE直接噴錯
CS0019 Operator '+' cannot be applied to operands of type 'Gil' and 'Gil'

參考
運算子多載

之前技巧1 處理相等時 只有寫 operator == 跟!=
(相等的部分請看一下技巧1)
把加減乘除也補上吧

void Main()
{
    var gil1 = new Gil(50);
    var gil2 = new Gil(25);
    (gil1 + gil2).ToString().Dump("gil1 + gil2");
    (gil1 - gil2).ToString().Dump("gil1 - gil2");
    (gil1 * gil2).ToString().Dump("gil1 * gil2");
    (gil1 / gil2).ToString().Dump("gil1 / gil2");
}
public class Gil
{
    public int Amount { get; set; }
    public string CurrencyName { get; } = "GD";
    public Gil(int amount)
    {
        Amount = amount;
    }
    public override string ToString() => $"{Amount} {CurrencyName}";

    public static Gil operator +(Gil a) => a;
    public static Gil operator -(Gil a) => new Gil(-a.Amount);

    public static Gil operator +(Gil a, Gil b)
        => new Gil(a.Amount + b.Amount);

    public static Gil operator -(Gil a, Gil b)
        => a + (-b);

    public static Gil operator *(Gil a, Gil b)
        => new Gil(a.Amount * b.Amount);

    public static Gil operator /(Gil a, Gil b)
    {
        if (b.Amount == 0) throw new DivideByZeroException();

        return new Gil(a.Amount / b.Amount);
    }
}

結束試煉

加減乘除比較少用到 自訂物件跟數相關的也不多

如果內容有誤請多鞭策謝謝