class Program { static void Main(string[] args) { Console.WriteLine("http://www.itsvse.com"); HashSet<Test1> list1 = new HashSet<Test1>(); HashSet<Test2> list2 = new HashSet<Test2>(); HashSet<string> list3 = new HashSet<string>(); list1.Add(new Test1(1, "a")); list1.Add(new Test1(2, "b")); list1.Add(new Test1(3, "c")); list1.Add(new Test1(4, "d")); list1.Add(new Test1(4, "d")); list2.Add(new Test2(1, "a")); list2.Add(new Test2(2, "b")); list2.Add(new Test2(3, "c")); list2.Add(new Test2(4, "d")); list2.Add(new Test2(4, "d")); list3.Add("1"); list3.Add("2"); list3.Add("3"); list3.Add("4"); list3.Add("4"); Console.WriteLine("输出list1"); foreach (var item in list1) { Console.WriteLine(item.id); } Console.WriteLine("输出list2"); foreach (var item in list2) { Console.WriteLine(item.id); } Console.WriteLine("输出list3"); foreach (var item in list3) { Console.WriteLine(item); } Console.ReadKey(); } } public class Test1 { public Test1(long i,string str) { this.id = i; this.a = str; } public long id { get; set; } public string a { get; set; } } public class Test2 { public Test2(long i, string str) { this.id = i; this.a = str; } public long id { get; set; } public string a { get; set; } public override bool Equals(object obj) { Test2 e = obj as Test2; return this.id == e.id && this.a == e.a; } public override int GetHashCode() { return this.id.GetHashCode() + this.a.GetHashCode(); } }
1,如果hash码值不相同,说明是一个新元素,存;
2,如果hash码值相同,且equles判断相等,说明元素已经存在,不存;
3,如果hash码值相同,且equles判断不相等,说明元素不存在,存;
我们Test2对象,重写了对象的的equals和hashCode方法。这里让Test2对象,只要是id和a相同就认为是相同的实例,当然也可以是其他,这就要看具体需求