.net -笔记 简单的操作符重载
这个操作符重载很有意思
class program
{
static void main(string[] args)
{
person person1 = new person() { name = "lilei", age = 12 };
person person2 = new person("hanmeimei", 11);
person person3 = person1 + person2;
person person4 = person1 == person2;
person person5 = 10;
console.writeline($"name's merge is {person3.name}\nage's sum is {person3.age}");
console.readkey();
}
}
public class person
{
public person() { }
public person(string name, int age)
{
this.name = name; this.age = age;
}
public string name { get; set; }
public int age { get; set; }
public static person operator +(person p1, person p2)
{
person p3 = new person(p1.name + p2.name, p1.age + p2.age);
return p3;
}
public static person operator ==(person p1, person p2)
{
person p3 = new person(p1.name + p2.name, p1.age + p2.age);
return p3;
}
public static person operator !=(person p1, person p2)
{
person p3 = new person(p1.name + p2.name, p1.age + p2.age);
return p3;
}
public static implicit operator person(int age)
{
return new person();
}
}
推荐阅读