C# 隱式轉換關鍵字 implicit

implicit 關鍵字用於聲明隱式的用戶定義類型轉換運算符。 若是能夠確保轉換過程不會形成數據丟失,則可以使用該關鍵字在用戶定義類型和其餘類型之間進行隱式轉換。code

引用摘自:implicit(C# 參考)ci

仍以Student求和舉例get

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

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

不使用implicit 求和數學

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

            //a的總成績 語文和數據的總分數
            Console.WriteLine(a.Chinese + a.Math);          
        }
    }

使用implicitstring

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

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

        /// <summary>
        /// 隱式求和
        /// </summary>
        /// <param name="a"></param>
        public static implicit operator double(Student a)
        {
            return a.Chinese + a.Math;
        }
    }

求和:it

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

            double total = a;

            //a的總成績 語文和數據的總分數
            Console.WriteLine(total);
        }
    }
相關文章
相關標籤/搜索