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

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

    GetHashCode's result is supposed to be:

    1. As fast as possible.
    2. As unique as possible.

    Bearing those in mind, I would go with something like this:

    if (str1 == null)
        if (str2 == null)
            return 0;
        else
           return str2.GetHashCode();
    else
        if (str2 == null)
            return str1.GetHashCode();
        else
           return ((ulong)str1.GetHashCode() | ((ulong)str2.GetHashCode() << 32)).GetHashCode();
    

    Edit: Forgot the nulls. Code fixed.

提交回复
热议问题