如何实现GetHash code的结构两个字符串,当两个字符串是可以互换 [英] How do you implement GetHashCode for structure with two string, when both strings are interchangeable

查看:96
本文介绍了如何实现GetHash code的结构两个字符串,当两个字符串是可以互换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C#中的结构:

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

   public string str2
   {
     get;
     set;
   }   
}

唯一的规则是,的UserInfo(STR1 =AA,str2的=BB)。等于(的UserInfo(STR1 =BB,str2的=AA))

如何覆盖这种结构的GetHash code函数?

How to override the GetHashCode function for this structure?

推荐答案

MSDN

一个哈希函数必须具有以下属性:

A hash function must have the following properties:


      
  • 如果两个对象的比较结果相等,每个对象的 GetHash code 方法必须返回相同的值。但是,如果两个对象不比较结果相等,两个对象的 GetHash code 方法不必返回不同的值。

  •   
  • 为对象的 GetHash code 方法必须一致,只要没有修改,确定该对象的状态返回相同的哈希code对象的返回值等于方法。注意,这是真实的,只有一个应用程序的当前执行,并能应用程序是否再次运行被返回不同的散列code

  •   
  • 为了获得最佳性能,哈希函数必须为所有输入生成随机分布。

  •   
  • 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

这篇关于如何实现GetHash code的结构两个字符串,当两个字符串是可以互换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆