亲宝软件园·资讯

展开

C#中Equals和GetHashCode使用及区别

人气:0

Equals和GetHashCode

Equals每个实现都必须遵循以下约定:

GetHashCode:

IEqualityComparer实现

下面我们创建一个学生类,从而进一步的实现我们对象数据的对比

 public class Student
 {
  public string Name { get; set; }

  public int Age { get; set; }
 }

通过如下代码我们将通过distinct方法实现我们的过滤.

 class Program
 {
  static void Main(string[] args)
  {
   List<Student> students = new List<Student>
   {
    new Student{ Name = "MR.A", Age = 32},
    new Student{ Name = "MR.B", Age = 34},
    new Student{ Name = "MR.A", Age = 32} 
   };
   Console.WriteLine("distinctStudents has Count = {0}", students.Distinct().Count());//distinctStudents has Count = 3
   Console.ReadLine();
  }
 }

我们需要达到的是忽略相同数据的对象,但是并没有达到我们如期的效果.因为是distinct默认比较的是对象的引用...所以这样达不到我们预期效果.那我们修改一下来实现我们预期效果.

在默认情况下Equals具有以下行为:

Distinct(IEnumerable, IEqualityComparer)

通过使用指定的 IEqualityComparer 对值进行比较,返回序列中的非重复元素.

类型参数

参数

返回

一个包含源序列中的非重复元素的 IEnumerable。

我们来看如下代码片段

 public class StudentComparator : EqualityComparer<Student>
 {
  public override bool Equals(Student x,Student y)
  {
   return x.Name == y.Name && x.Age == y.Age;
  }

  public override int GetHashCode(Student obj)
  {
   return obj.Name.GetHashCode() * obj.Age;
  }
 }

上述代码片段如果两个Equals返回的true并且GetHashCode返回相同的哈希码,则认为两个对象相等.

重写Equals和GetHashCode

var stu1 = new Student { Name = "MR.A", Age = 32 };
var stu2 = new Student { Name = "MR.A", Age = 32 };
bool result = stu1.Equals(stu2); //false because it's reference Equals

   上述代码片段执行后结果非预期效果.我们将进一步的去实现代码,以达到预期效果....

 public class Student
 {
  public string Name { get; set; }

  public int Age { get; set; }

  public override bool Equals(object obj)
  {
   var stu = obj as Student;
   if (stu == null) return false;
   return Name == stu.Name && Age == stu.Age; 
  }
  public override int GetHashCode()
  {
   return Name.GetHashCode() * Age;
  }
 }
 
 var stu1 = new Student { Name = "MR.A", Age = 32 };
 var stu2 = new Student { Name = "MR.A", Age = 32 };

 bool result = stu1.Equals(stu2); //result is true

我们再使用LINQ Distinct方法进行过滤和查询,同时将会检查Equals和GetHashCode

 List<Student> students = new List<Student>
 {
  new Student{ Name = "MR.A", Age = 32},
  new Student{ Name = "MR.B", Age = 34},
  new Student{ Name = "MR.A", Age = 32}
 };
 Console.WriteLine("distinctStudents has Count = {0}", students.Distinct().Count()); //distinctStudents has Count = 2

作者:@冯辉
出处:https://www.cnblogs.com/yyfh/p/12245916.html?utm_source=tuicool&utm_medium=referral

您可能感兴趣的文章:

加载全部内容

相关教程
猜你喜欢
用户评论