首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >是否可以依赖GetHashCode()的值来保持一致?

是否可以依赖GetHashCode()的值来保持一致?
EN

Stack Overflow用户
提问于 2018-07-31 06:01:39
回答 2查看 0关注 0票数 0

假设使用相同的字符串值,GetHashCode()的返回值是否保证是一致的?(C#/ASP.NET)

今天我把代码上传到服务器上,令我惊讶的是,我不得不重新索引一些数据,因为我的服务器(Win 2008 64位)返回的值与我的桌面计算机不同。

EN

回答 2

Stack Overflow用户

发布于 2018-07-31 14:15:51

代码语言:txt
复制
    /// <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;
    }

此实现可能比之前发布的不安全实现要慢。但更简单更安全。

票数 0
EN

Stack Overflow用户

发布于 2018-07-31 15:19:42

实现取决于框架的版本,但也取决于体系结构。string.GetHashCode()的实现在框架的x86和x64版本中是不同的,即使它们具有相同的版本号。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100000463

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档