List<T>.Contains(T item)为什么我把两封一样的邮件经分析后一模一样的数据mail

it2022-05-05  153

方法1:

static void Main(string[] args) { TestClass tc1 = new TestClass(); tc1.i = 1; TestClass tc2 = new TestClass(); tc2.i = 1; List<TestClass> list = new List<TestClass>(); list.Add(tc1); Console.WriteLine(list.Contains(tc2)); Console.WriteLine(list.Contains(tc2, new TestComparer<TestClass>())); } class TestClass { public int i; } class TestComparer<T> : IEqualityComparer<T> where T : TestClass { public int GetHashCode(T obj) { return obj.GetHashCode(); } public bool Equals(T t1, T t2) { return t1.i == t2.i; } }

方法2:

引用类型,需要重载Mail_DATA类的Equals()函数: public override bool Equals(System.Object obj) { // If parameter is null return false. if (obj == null) { return false; } // If parameter cannot be cast to Mail_DATA return false. Mail_DATA c = obj as Mail_DATA; if ((System.Object)c == null) { return false; } // Return true if the fields match: return (this.属性1== c.属性1) && (this.属性2== c.属性2)&&...;//这里根据需要确定,哪些属性能够确定两个对象equal的列出 }

转载于:https://www.cnblogs.com/hongjiumu/archive/2012/09/10/2678862.html


最新回复(0)