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

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

    A simple general way is to do this:

    return string.Format("{0}/{1}", str1, str2).GetHashCode();
    

    Unless you have strict performance requirements, this is the easiest I can think of and I frequently use this method when I need a composite key. It handles the null cases just fine and won't cause (m)any hash collisions (in general). If you expect '/' in your strings, just choose another separator that you don't expect.

提交回复
热议问题