当自定义一个类的时候,如果需要用到对比的功能,可以自己重写Equals方法,最整洁的方法是重写GetHashCode()方法。
public enum Week { Monday = 1, Tuesday = 2, Wednesday = 3, Thursday = 4, Friday = 5, Saturday = 6, Sunday = 0 } public class TestEquals { public Week Day { get; set; } public string Name { get; set; } public int Age { get; set; } public TestEquals(Week day, string name, int age) { this.Day = day; this.Name = name; this.Age = age; } public override bool Equals(object obj) { if (obj == null) return false; if (obj.GetType() != this.GetType()) return false; TestEquals p = obj as TestEquals; return this.GetHashCode() == p.GetHashCode(); } public override int GetHashCode() { return Day.GetHashCode() ^ Name.GetHashCode() ^ Age.GetHashCode(); } }
static void Main(string[] args) { TestEqual(); } private static void TestEqual() { TestEquals t1 = new TestEquals(Week.Monday, "杨彬", 29); TestEquals t2 = new TestEquals(Week.Monday, "杨彬", 29); Console.WriteLine(t1.Equals(t2)); Console.ReadLine(); }
原文:http://www.cnblogs.com/takako_mu/p/3569548.html