问题
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