zoukankan      html  css  js  c++  java
  • 重载运算符

    在开发过程中,一定会有元算,下面的运算一目了然,是大家喜见乐闻的。

    static void Main(string[] args) 
    {
         int x = 5;
         int y = 6;
         int sum = x + y;
         Console.WriteLine(sum);
     }

    可是如果成了这样,我们就有必要F12进去看一下了(当然这个简单的不用,可是要是复杂的,你能不进去吗)。

    static void Main(string[] args)
     {
         int x = 5;
         int y = 6;
         int sum = Add(x, y);
         Console.WriteLine(sum); 
    } 
    static int Add(int x, int y) 
    {
         return x + y; 
    }

    如果现在有一个类,需要得知两个类某个属性的和,我们可能会这样:

    namespace Program 
    {
         //重载运算符
         class Program
         {
             static void Main(string[] args)
             {
                 Person PA = new Person("xiaoA", 20);
                 Person PC = new Person("xiaoC", 21);
                 int TotalAge = Add(PA.age , PC.age);
                 Console.WriteLine(TotalAge);
             }
             static int Add(int x, int y)
             {
                 return x + y;
             }
         }
    
        class Person
         {
             public string name { get; set; }
             public int age { get; set; }
             public Person() { }
             public Person(string _name) { this.name = _name; }
             public Person(string _name, int _age) { this.name = _name; this.age = _age; }     }
    
    }

    如果我们重写了运算符 “+” 就不用那么麻烦了

    namespace Program
     {
         //重载运算符
         class Program
         {
             static void Main(string[] args)
             {
                 Person PA = new Person("xiaoA", 20);
                 Person PC = new Person("xiaoC", 21);
                 int TotalAge = PA + PC;
                 Console.WriteLine(TotalAge);
             }
         }
    
        class Person
         {
             public string name { get; set; }
             public int age { get; set; }
             public Person() { }
             public Person(string _name) { this.name = _name; }
             public Person(string _name, int _age) { this.name = _name; this.age = _age; }
             public static int operator +(Person p1, Person p2)
             {
                 return p1.age + p2.age;
             }
         }
    
    }
  • 相关阅读:
    javaScript 中的异步编程
    javaScript内存泄漏
    javaScript| 对象的拷贝
    javaScript 数组的拷贝
    javaScript 去除数组中的重复值
    解决js key中的时间间隔
    js未命题(杂记)
    js中斐波拉切数的三种写法;
    js闭包的七中形式
    Javascript学习日志(三):闭包
  • 原文地址:https://www.cnblogs.com/Jolinson/p/3490921.html
Copyright © 2011-2022 走看看