C#operator關鍵字自定義運算子

個人天使發表於2019-05-11

理解 : 用於定義用運算,或提供類或結構宣告中的使用者定義轉換

用法:

class Program
{
    static void Main(string[] args)
    {
        Apple data = new Apple(100,205);
        Apple data1 = new Apple(12,250);
        double s = data1;
        string a = data;
        var newdata = data1 * data;
        Console.WriteLine(a+"\n"+ s+"\n"+newdata.A+"\n"+newdata.B+ "\n" + newdata.C+ "\n" + newdata.D);   
    }
}
public class Apple
{
  public   int A, B
    public Apple(int a,int b)
    {
        this.A = a;this.B = b;
    }
    public Apple(Apple Data)
    {
        A = Data.A;
        B = Data.B;
    }
    public static Apple operator +(Apple a, Apple b)
    {
        Apple apple = new Apple(a);
        apple.A += b.A;
        apple.B += b.B;
        return apple;
    }
    public static Apple operator -(Apple a, Apple b)
    {
        Apple apple = new Apple(a);
        apple.A -= b.A;
        apple.B -= b.B;
        return apple;
    }
    public static implicit  operator double (Apple a)
    {
        return a.A;
    }
    public static implicit operator string(Apple a)
    {
        return a.B.ToString();
    }
    public static Apple operator*(Apple a, Apple b)
    {
        Apple apple = new Apple(a);
        apple.A *= b.A;
        apple.B *= b.B;
        return apple;
    }

    public static Apple operator /(Apple a, Apple b)
    {
        Apple apple = new Apple(a);
        apple.A /= b.A;
        apple.B /= b.B;
        return apple;
    }
}

龐順龍最後編輯於:3年前

內容均為作者獨立觀點,不代表八零IT人立場,如涉及侵權,請及時告知。

相關文章