GetHashCode for the object with several data members

我们两清 提交于 2019-12-08 12:39:15

问题


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();
         }
     }
}

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


回答1:


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)
}


来源:https://stackoverflow.com/questions/22324403/gethashcode-for-the-object-with-several-data-members

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!