IEqualityComparer<T>接口的對象的主要做用在於自定義判斷兩個對象是否相等。javascript
其中最經常使用的方法: bool Equals(T x, T y);html
實現該方法用於比較兩個對象是否相等。若是指定的對象相等,則爲 true;不然爲 false。java
代碼示例:git
class Program { static void Main(string[] args) { People p1 = new People(1, "劉備", 23); People p2 = new People(1, "關羽", 22); People p3 = new People(1, "張飛", 21); List<People> listP1 = new List<People>(); listP1.Add(p1); listP1.Add(p2); listP1.Add(p3); People p4 = new People(2, "趙雲", 23); People p5 = new People(2, "黃忠", 22); People p6 = new People(2, "馬超", 21); List<People> listP2 = new List<People>(); listP2.Add(p4); listP2.Add(p5); listP2.Add(p6); Comparers c = new Comparers(); bool b = listP1.SequenceEqual(listP2, c); //只要集合中的對象年齡相等就視對象爲相等 Console.WriteLine(b); //輸出 True Console.ReadKey(); } } public class Comparers : IEqualityComparer<People> { public bool Equals(People p1, People p2) { if (p1.Age == p2.Age) { return true; } return false; } public int GetHashCode(People obj) { throw new NotImplementedException(); } } public class People { public People(int id, string name, int age) { this.Id = id; this.Name = name; this.Age = age; } public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } }