這個操作符重載很有意思 class Program { static void Main(string[] args) { Person person1 = new Person() { Name = "LiLei", Age = 12 }; Person person2 = new Person( ...
這個操作符重載很有意思
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();
}
}