C# 轉換關鍵字 operator

operator

使用 operator 關鍵字重載內置運算符,或在類或結構聲明中提供用戶定義的轉換。code

假設場景,一個Student類,有語文和數學兩科成績,Chinese Math,加減兩科成績,不重載運算,代碼以下。get

class Student
    {
        /// <summary>
        /// 語文成績
        /// </summary>
        public double Chinese { get; set; }

        /// <summary>
        /// 數學成績
        /// </summary>
        public double Math { get; set; }
    }

比較兩個成績差距數學

var a = new Student
            {
                Chinese = 90.5d,
                Math = 88.5d
            };

            var b = new Student
            {
                Chinese = 70.5d,
                Math = 68.5d
            };

            //a的語文比b的語文高多少分
            Console.WriteLine(a.Chinese - b.Chinese);
            //a的數學比b的數學高多少分
            Console.WriteLine(a.Math - b.Math);

使用operator 重載 -string

class Student
    {
        /// <summary>
        /// 語文成績
        /// </summary>
        public double Chinese { get; set; }

        /// <summary>
        /// 數學成績
        /// </summary>
        public double Math { get; set; }

        public static Student operator -(Student a, Student b)
        {
            return new Student
            {
                Chinese = a.Chinese - b.Chinese,
                Math = a.Math - b.Math
            };
        }
    }

比較成績差距的代碼能夠改成it

class Program
    {
        static void Main(string[] args)
        {
            var a = new Student
            {
                Chinese = 90.5d,
                Math = 88.5d
            };

            var b = new Student
            {
                Chinese = 70.5d,
                Math = 68.5d
            };

            var c = a - b;
            //a的語文比b的語文高多少分
            Console.WriteLine(c.Chinese);
            //a的數學比b的數學高多少分
            Console.WriteLine(c.Math);
        }
    }

參考:運算符(C# 參考)class

相關文章
相關標籤/搜索