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
最新推荐文章于 2023-06-12 22:15:27 发布