跳轉到內容

C# 程式設計/關鍵字/運算子

來自華夏公益教科書,開放書籍,開放世界

operator 關鍵字允許類過載算術運算子和強制轉換運算子

public class Complex
{
    private double re, im;
    
    public double Real
    {
        get { return re; }
        set { re = value; }
    }
    
    public double Imaginary
    {
        get { return im; }
        set { im = value; }
    }
    
    // binary operator overloading
    public static Complex operator +(Complex c1, Complex c2)
    {
        return new Complex() { Real = c1.Real + c2.Real, Imaginary = c1.Imaginary + c2.Imaginary };
    }
    
    // unary operator overloading
    public static Complex operator -(Complex c)
    {
        return new Complex() { Real = -c.Real, Imaginary = -c.Imaginary };
    }
    
    // cast operator overloading (both implicit and explicit)
    public static implicit operator double(Complex c)
    {
        // return the modulus: sqrt(x^2 + y^2)
        return Math.Sqrt(Math.Pow(c.Real, 2) + Math.Pow(c.Imaginary, 2));
    }
    
    public static explicit operator string(Complex c)
    {
        // we should be overloading the ToString() method, but this is just a demonstration
        return c.Real.ToString() + " + " + c.Imaginary.ToString() + "i";
    }
}

public class StaticDemo
{
    public static void Main()
    {
        Complex number1 = new Complex() { Real = 1, Imaginary = 2 };
        Complex number2 = new Complex() { Real = 4, Imaginary = 10 };
        Complex number3 = number1 + number2; // number3 now has Real = 5, Imaginary = 12
        
        number3 = -number3; // number3 now has Real = -5, Imaginary = -12
        double testNumber = number3; // testNumber will be set to the absolute value of number3
        Console.WriteLine((string)number3); // This will print "-5 + -12i".
        // The cast to string was needed because that was an explicit cast operator.
    }
}



C# 關鍵字
抽象 作為 基地 布林值 休息
位元組 案件 捕捉 字元 已檢查
常數 繼續 十進位制 預設
委託 雙精度 否則 列舉
事件 顯式 外部 最後
固定 浮動 為了 每一個 轉到
如果 隱式 整數 介面
內部 名稱空間
物件 運算子 外出
覆蓋 引數 私有 受保護的 公共的
只讀 參考 返回 位元組 密封的
大小 堆疊分配 靜態 字串
結構 開關 這個 丟擲 真的
嘗試 型別 無符號整數 無符號長整型 未經檢查
不安全 無符號短整型 使用 變數 虛擬
易失
特殊的 C# 識別符號(上下文關鍵字)
新增 別名 非同步 等待 動態
得到 全球 名稱 區域性 刪除
設定 價值 什麼時候 哪裡 產量
上下文關鍵字(用於查詢)
上升 下降 等於
群體 進入 加入
排序 選擇 哪裡
華夏公益教科書