zoukankan      html  css  js  c++  java
  • C# 转换关键字 operator

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

  • 相关阅读:
    HDU 3033 I love sneakers!
    HDU 1712 ACboy needs your help
    FZU 1608 Huge Mission
    HDU 3394 Railway
    【MySQL】20个经典面试题,全部答对月薪10k+
    mysql故障解决笔记
    mysql 索引类型
    linux禁用锁定和解除解锁用户账号的方法
    Linux服务器制定mysql数据库备份的计划任务
    网站服务器安全防范小知识
  • 原文地址:https://www.cnblogs.com/AlienXu/p/9482719.html
Copyright © 2011-2022 走看看