重载运算符

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

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

}

 

 

posted on 2013-12-25 16:30  Aidou_dream  阅读(213)  评论(0编辑  收藏  举报

导航