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

这个操作符重载很有意思

class Pro­gram
{
sta­t­ic void Main(string[] args)
{
Per­son person1 = new Per­son() { Name = “LiLei”, Age = 12 };
Per­son person2 = new Person(“HanMeimei”, 11);
Per­son person3 = person1 + person2;
Per­son person4 = person1 == person2;
Per­son person5 = 10;
Console.WriteLine($“Name’s merge is {person3.Name}\nAge’s sum is {person3.Age}”);
Console.ReadKey();
}
}

pub­lic class Person
{
pub­lic Person() { }
pub­lic Person(string name, int age)
{
this.Name = name; this.Age = age;
}
pub­lic string Name { get; set; }
pub­lic int Age { get; set; }
pub­lic sta­t­ic Per­son oper­a­tor +(Per­son p1, Per­son p2)
{
Per­son p3 = new Person(p1.Name + p2.Name, p1.Age + p2.Age);
return p3;
}

pub­lic sta­t­ic Per­son oper­a­tor ==(Per­son p1, Per­son p2)
{
Per­son p3 = new Person(p1.Name + p2.Name, p1.Age + p2.Age);
return p3;
}
pub­lic sta­t­ic Per­son oper­a­tor !=(Per­son p1, Per­son p2)
{
Per­son p3 = new Person(p1.Name + p2.Name, p1.Age + p2.Age);
return p3;
}

pub­lic sta­t­ic implic­it oper­a­tor Person(int age)
{
return new Person();
}
}

为您推荐

发表评论

电子邮件地址不会被公开。 必填项已用*标注