假设使用相同的字符串值,GetHashCode()的返回值是否保证是一致的?(C#/ASP.NET)
今天我把代码上传到服务器上,令我惊讶的是,我不得不重新索引一些数据,因为我的服务器(Win 2008 64位)返回的值与我的桌面计算机不同。
发布于 2018-07-31 14:15:51
/// <summary>
/// Default implementation of string.GetHashCode is not consistent on different platforms (x32/x64 which is our case) and frameworks.
/// FNV-1a - (Fowler/Noll/Vo) is a fast, consistent, non-cryptographic hash algorithm with good dispersion. (see http://isthe.com/chongo/tech/comp/fnv/#FNV-1a)
/// </summary>
private static int GetFNV1aHashCode(string str)
{
if (str == null)
return 0;
var length = str.Length;
// original FNV-1a has 32 bit offset_basis = 2166136261 but length gives a bit better dispersion (2%) for our case where all the strings are equal length, for example: "3EC0FFFF01ECD9C4001B01E2A707"
int hash = length;
for (int i = 0; i != length; ++i)
hash = (hash ^ str[i]) * 16777619;
return hash;
}
此实现可能比之前发布的不安全实现要慢。但更简单更安全。
发布于 2018-07-31 15:19:42
实现取决于框架的版本,但也取决于体系结构。string.GetHashCode()的实现在框架的x86和x64版本中是不同的,即使它们具有相同的版本号。
https://stackoverflow.com/questions/-100000463
复制相似问题