How do you implement GetHashCode for structure with two string, when both strings are interchangeable

前端 未结 14 2039
余生分开走
余生分开走 2020-12-08 09:05

I have a structure in C#:

public struct UserInfo
{
   public string str1
   {
     get;
     set;
   }

   public string str2
   {
     get;
     set;
   }           


        
14条回答
  •  天涯浪人
    2020-12-08 09:39

    Going along the lines ReSharper is suggesting:

    public int GetHashCode()
    {
        unchecked
        {
            int hashCode;
    
            // String properties
            hashCode = (hashCode * 397) ^ (str1!= null ? str1.GetHashCode() : 0);
            hashCode = (hashCode * 397) ^ (str2!= null ? str1.GetHashCode() : 0);
    
            // int properties
            hashCode = (hashCode * 397) ^ intProperty;
            return hashCode;
        }
    }
    

    397 is a prime of sufficient size to cause the result variable to overflow and mix the bits of the hash somewhat, providing a better distribution of hash codes. Otherwise there's nothing special in 397 that distinguishes it from other primes of the same magnitude.

提交回复
热议问题