using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication23
{
class Program
{
static void Main()
{
PersonComparer pc = new PersonComparer();
Person p = new Person { Name = "张三", Age = 14 };
Person p1 = new Person { Name = "张三", Age = 14 };
List<Person> personList = new List<Person>();
personList.Add(p);
if (!personList.Contains(p1, pc))
personList.Add(p1);
Console.Read();
}
}
class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
class PersonComparer : IEqualityComparer<Person>
{
public bool Equals(Person x, Person y)
{
if (x.Name.Equals(y.Name))
return true;
else
return false;
}
public int GetHashCode(Person p)
{
int code = p.Name.GetHashCode() ^ p.Age;
return code.GetHashCode();
}
}
}
C# IEqualityComparer
最新推荐文章于 2025-10-30 17:40:08 发布
本文介绍了一种在C#中实现自定义对象比较的方法,通过创建实现了IEqualityComparer接口的PersonComparer类来判断两个Person对象是否相等。该示例重点展示了如何根据对象的特定属性(如姓名)进行比较,并提供了 GetHashCode 方法的一个示例实现。
1363

被折叠的 条评论
为什么被折叠?



