C# 显式转换关键字 explicit

不同于隐式转换,显式转换运算符必须通过转换的方式来调用。 如果转换操作会导致异常或丢失信息,则应将其标记为 explicit。 这可阻止编译器静默调用可能产生意外后果的转换操作。
省略转换将导致编译时错误 CS0266。

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

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

该引用摘自:使用转换运算符(C# 编程指南)

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

    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

    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 Program
    {
        static void Main(string[] args)
        {
            var a = new Student
            {
                Chinese = 90.5d,
                Math = 88.5d
            };

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

猜你喜欢

转载自www.cnblogs.com/AlienXu/p/9483726.html