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

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

    MSDN:

    A hash function must have the following properties:

    • If two objects compare as equal, the GetHashCode method for each object must return the same value. However, if two objects do not compare as equal, the GetHashCode methods for the two object do not have to return different values.
    • The GetHashCode method for an object must consistently return the same hash code as long as there is no modification to the object state that determines the return value of the object's Equals method. Note that this is true only for the current execution of an application, and that a different hash code can be returned if the application is run again.
    • For the best performance, a hash function must generate a random distribution for all input.

    Taking it into account correct way is:

    return str1.GetHashCode() ^ str2.GetHashCode() 
    

    ^ can be substituted with other commutative operation

    0 讨论(0)
  • 2020-12-08 09:50
    public override int GetHashCode()   
    {       
        unchecked      
        {           
            return(str1 != null ? str1.GetHashCode() : 0) ^ (str2 != null ? str2.GetHashCode() : 0);       
        }   
    }
    
    0 讨论(0)
提交回复
热议问题