来自 电脑系统 2019-11-28 05:52 的文章
当前位置: 金沙澳门官网网址 > 电脑系统 > 正文

隐式调换关键字,显式转变关键字

求和:

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

            double total = a;

            //a的总成绩 语文和数据的总分数
            Console.WriteLine(total);
        }
    }

仍以Student为例,取语文和数学成绩的和,不使用explicit

求和:

显示转换关键字explicit能向阅读代码的每个人清楚地指示您要转换类型。

不使用implicit 求和

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

        /// <summary>
        /// 数学成绩
        /// </summary>
        public double Math { get; set; }

        public static explicit operator double(Student a)
        {
            return a.Chinese + a.Math;
        }
    }
    class Student
    {
        /// <summary>
        /// 语文成绩
        /// </summary>
        public double Chinese { get; set; }

        /// <summary>
        /// 数学成绩
        /// </summary>
        public double Math { get; set; }
    }
    class Student
    {
        /// <summary>
        /// 语文成绩
        /// </summary>
        public double Chinese { get; set; }

        /// <summary>
        /// 数学成绩
        /// </summary>
        public double Math { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            var a = new Student
            {
                Chinese = 90.5d,
                Math = 88.5d
            };

            //a的总成绩 语文和数据的总分数
            Console.WriteLine(a.Chinese + a.Math);          
        }
    }

该引用摘自:explicit(C# 参考)

    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;
        }
    }

本文由金沙澳门官网网址发布于电脑系统,转载请注明出处:隐式调换关键字,显式转变关键字

关键词: