GetHashCode返回不同​​的值

发布于 2025-01-12 16:48:02 字数 354 浏览 1 评论 0原文

如果我在 .Net Framework 4.5.2 控制台应用程序上运行此代码:

var test = "test";
var testHashCode = test.GetHashCode();

testHashCode 的值为:-871206010

当我在.Net Framework 4.5.2 wcf 服务,testHashCode 值为-354185609。为什么会有差异?

If I run this code on .Net Framework 4.5.2 console app:

var test = "test";
var testHashCode = test.GetHashCode();

value of testHashCode is: -871206010

When I run the same code on .Net Framework 4.5.2 wcf service, value of testHashCode is -354185609. Why there is a difference?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

感悟人生的甜 2025-01-19 16:48:02

GetHashCode() 并不是一个可靠的永久哈希函数;所需要的、预期的和记录的只是在相同的程序执行中,它应该(如果正确实现)为等于 true 的输入返回相同的输出(另见:脚注)。对于不同的进程(甚至同一进程中的不同应用程序域),输出可能不同。这甚至是可取的,以防止基于可预测的哈希行为的某些类型的字典饱和攻击。这些规则当然可以在框架版本、操作系统等之间改变——例如,这可以提高实现的性能。

所以基本上:对于你似乎想要的东西:使用 SHA 或其他一些稳定的哈希算法,而不是 GetHashCode()

(脚注:它没有说明为等于 false 的输入返回不同的输出)

GetHashCode() is not intended to be a reliable permanent hash function; all that is required, intended and documented is that inside the same program execution, it should (if correctly implemented) return the same output for inputs that equate as true (see also: footnote). For different processes (or even different app-domains in the same process), the output can be different. This can even be desirable, to prevent some kinds of dictionary saturation attacks based on predictable hashing behaviour. The rules can certainly change between framework versions, operating systems, etc - this allows, for example, for performance improvements to the implementation.

So basically: for what you seem to want: use something like SHA or some other stable hashing algorith, not GetHashCode().

(footnote: it doesn't say anything about returning different output for inputs that equate as false)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文