当前位置: 移动技术网 > IT编程>开发语言>.net > C# 转换关键字 operator

C# 转换关键字 operator

2018年08月17日  | 移动技术网IT编程  | 我要评论

优播图库,9887地铁笨蛋6,电讯一代

operator

使用 operator 关键字重载内置运算符,或在类或结构声明中提供用户定义的转换。

假设场景,一个student类,有语文和数学两科成绩,chinese math,加减两科成绩,不重载运算,代码如下。

    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 重载 -

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

比较成绩差距的代码可以改为

    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# 参考)

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网