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

前端 未结 14 2043
余生分开走
余生分开走 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:32

    public override int GetHashCode()
    {
        unchecked
        {
            return (str1 ?? String.Empty).GetHashCode() +
                (str2 ?? String.Empty).GetHashCode();
        }
    }
    

    Using the '+' operator might be better than using '^', because although you explicitly want ('AA', 'BB') and ('BB', 'AA') to explicitly be the same, you may not want ('AA', 'AA') and ('BB', 'BB') to be the same (or all equal pairs for that matter).

    The 'as fast as possible' rule is not entirely adhered to in this solution because in the case of nulls this performs a 'GetHashCode()' on the empty string rather than immediately return a known constant, but even without explicitly measuring I am willing to hazard a guess that the difference wouldn't be big enough to worry about unless you expect a lot of nulls.

提交回复
热议问题