的GetHashCode为对象与多个数据成员 [英] GetHashCode for the object with several data members

查看:130
本文介绍了的GetHashCode为对象与多个数据成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class MyClass
{
   public string x;
   public string y;
}

public class MyClassEqualityComparer : IEqualityComparer<MyClass>
{
     public int GetHashCode(MyClass myobj)
     {
         if(myObj == null)
         {
            return base.GetHashCode();
         }
         if (myObj.x != null && myObj.y != null)
         {
              return myObj.x.GetGashCode()^myObj.y.GetGashCode();
         }
     }
}



应该是什么,如果执行myObj.x或/和myObj.y是空

what should be the implementation if myObj.x or/and myObj.y are nulls

推荐答案

有关的散列码的唯一要求是,被认为是两个对象平等共享相同的散列码。

The only requirement for a hash code is that two objects that are considered equal share the same hash code.

可以,例如,空的属性。

You can, for example, use 0 for null properties

public int GetHashCode(MyClass myobj)
{
     if(myObj == null)
     {
        return base.GetHashCode();
     }
     return (myObj.x != null ? myObj.x.GetGashCode() : 0) ^ (myObj.y != null ? myObj.y.GetGashCode() : 0)
}

这篇关于的GetHashCode为对象与多个数据成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆