GetHashCode返回不同的值
如果我在 .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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
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)