using System; using System.Collections.Generic; using System.Xml.Serialization; class Person { public int Age { get; set; } public string Name { get; set; } public static bool operator ==(Person p, Person pp) { return p.Equals(pp); } public static bool operator !=(Person p, Person pp) { return !(p == pp); } protected bool Equals(Person other) { return Age == other.Age && string.Equals(Name, other.Name); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((Person)obj); } public override int GetHashCode() { unchecked { return (Age * 397) ^ (Name != null ? Name.GetHashCode() : 0); } } private sealed class AgeNameEqualityComparer : IEqualityComparer<Person> { public bool Equals(Person x, Person y) { if (ReferenceEquals(x, y)) return true; if (ReferenceEquals(x, null)) return false; if (ReferenceEquals(y, null)) return false; if (x.GetType() != y.GetType()) return false; return x.Age == y.Age && string.Equals(x.Name, y.Name); } public int GetHashCode(Person obj) { unchecked { return (obj.Age * 397) ^ (obj.Name != null ? obj.Name.GetHashCode() : 0); } } } } class Program { static void Main(string[] args) { var pa = new Person() { Age = 32, Name = "zxl" }; var pb = new Person() { Age = 32, Name = "zxl" }; Console.WriteLine(pa == pb);//调用重载运算符== Console.WriteLine(pa.Equals(pb));//调用equals Console.WriteLine(object.ReferenceEquals(pa, pb));//比较地址 } }