.net -笔记 简单的操作符重载

这个操作符重载很有意思

 

 1 class Program
 2 {
 3 static void Main(string[] args)
 4 {
 5 Person person1 = new Person() { Name = "LiLei", Age = 12 };
 6 Person person2 = new Person("HanMeimei", 11);
 7 Person person3 = person1 + person2;
 8 Person person4 = person1 == person2;
 9 Person person5 = 10;
10 Console.WriteLine($"Name's merge is {person3.Name}\nAge's sum is {person3.Age}");
11 Console.ReadKey();
12 }
13 }
14 
15 public class Person
16 {
17 public Person() { }
18 public Person(string name, int age)
19 {
20 this.Name = name; this.Age = age;
21 }
22 public string Name { get; set; }
23 public int Age { get; set; }
24 public static Person operator +(Person p1, Person p2)
25 {
26 Person p3 = new Person(p1.Name + p2.Name, p1.Age + p2.Age);
27 return p3;
28 }
29 
30 public static Person operator ==(Person p1, Person p2)
31 {
32 Person p3 = new Person(p1.Name + p2.Name, p1.Age + p2.Age);
33 return p3;
34 }
35 public static Person operator !=(Person p1, Person p2)
36 {
37 Person p3 = new Person(p1.Name + p2.Name, p1.Age + p2.Age);
38 return p3;
39 }
40 
41 public static implicit operator Person(int age)
42 {
43 return new Person();
44 }
45 }
View Code

 

posted @ 2018-08-23 16:11  小夏先生  阅读(427)  评论(2编辑  收藏  举报