試煉28 - 自訂 class 技巧4 轉換

2022 鐵人賽文 搬回點部落

開始試煉

繼續寫operator
自訂物件 也可以定義 true 跟 false
這樣就可以用if(a)了

void Main()
{
    var a = new Gil(10);
    var b = new Gil(0);
    if (a)
    {
        true.Dump("if(a)");
    }
    if (b)
    {

    }
    else
    {
        false.Dump("if(b)");
    }
}
public class Gil
{
    public int Amount { get; set; }
    public string CurrencyName { get; } = "GD";
    public Gil(int amount)
    {
        Amount = amount;
    }
    public static bool operator true(Gil x) => x.Amount > 0;
    public static bool operator false(Gil x) => x.Amount <= 0;

    public override string ToString() => $"{Amount} {CurrencyName}";
}

處理轉換

實做explicit 明確轉換,implicit 隱含轉換
像是 Gil 的 Amount 是其實是int 所以
int intGil = a;
Gil c = (Gil)50;
也是直接轉換是很方便的

void Main()
{
	int intGil = a;
	intGil.Dump("intGil");
	
	Gil c = (Gil)50;
	c.Dump("c");
}
public class Gil
{
	public int Amount { get; set; }
	public string CurrencyName { get; } = "GD";
	public Gil(int amount)
	{
		Amount = amount;
	}
	public static bool operator true(Gil x) => x.Amount > 0;
	public static bool operator false(Gil x) => x.Amount <= 0;

	public static implicit operator int(Gil x) => x.Amount;
	public static explicit operator Gil(int x) => new Gil(x);
	
	public override string ToString() => $"{Amount} {CurrencyName}";
}

結束試煉

自訂 class 四部曲 結束啦

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