GetHashCode on null fields?

前端 未结 2 1664
离开以前
离开以前 2021-02-07 03:30

How do I deal with null fields in GetHashCode function?

Module Module1
  Sub Main()
    Dim c As New Contact
         


        
相关标签:
2条回答
  • 2021-02-07 03:52

    As Jeff Yates suggested, the override in the answer would give the same hash for (name = null, address = "foo") as (name = "foo", address = null). These need to be different. As suggested in link, something similar to the following would be better.

    public override int GetHashCode()
    {
        unchecked // Overflow is fine, just wrap
        {
            int hash = 17;
            hash = hash * 23 + (Name == null ? 0 : Name.GetHashCode());
            hash = hash * 23 + (Address == null ? 0 : Address.GetHashCode());
        }
        return hash;
    }
    

    What is the best algorithm for an overridden System.Object.GetHashCode?

    0 讨论(0)
  • 2021-02-07 04:18

    Typically, you check for null and use 0 for that "part" of the hash code if the field is null:

    return (Name == null ? 0 : Name.GetHashCode()) ^ 
      (Address == null ? 0 : Address.GetHashCode());
    

    (pardon the C#-ism, not sure of the null check equivalent in VB)

    0 讨论(0)
提交回复
热议问题