有没有办法使 .NET Core GetHashCode 具有确定性 [英] Is there a way to make .NET Core GetHashCode deterministic

查看:33
本文介绍了有没有办法使 .NET Core GetHashCode 具有确定性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是浪费了几个小时的调试时间,然后才意识到与 .NET 不同的是,在 .NET Core 中,每次运行代码时 GetHashCode 都会返回不同的值.我完全理解这样做的理由.依赖哈希码值是一个非常糟糕的主意(比如序列化它们).我什至记得 Microsoft 的 .NET 内部构建(Core 之前)会更改每个构建的 GetHashCode 行为,因此没有人会对此感到满意.

I just wasted few hours of debugging before realizing that contrary to .NET, in .NET Core, GetHashCode returns a different value every time you run your code. I totally understand the rationale for this. Relying on hash code values is a very bad idea (like serializing them). I even remember that internal builds of .NET at Microsoft (prior to Core) would change the behavior of GetHashCode for every build so that nobody gets too comfortable with it.

说了这么多,我目前正在调试大量使用 GetHashCode 的复杂代码.我知道这个错误是我自己做的,与 GetHashCode 无关,但每次我运行它时,它都会在其他地方失败.很烦人.有没有办法强制 GetHashCode 表现得像在 .NET 中一样(在我调试时),而不必编写我自己的哈希函数并且不必在我的代码中的任何地方替换它?

Having said all this, I’m currently debugging complex code that makes heavy use of GetHashCode. I know the bug is my own doing and has nothing to do with GetHashCode but each time I run it, it fails elsewhere. Very annoying. Is there a way to force GetHashCode to behave like in .NET (while I’m debugging) without having to write my own hash function and having to replace it everywhere in my code?

推荐答案

我发现让 string.GetHashCode 在多次执行中返回可预测值的实用解决方案只是切换回经典 .NET (4.6).由于我的代码没有任何特定于 .NET Core 的内容,因此我唯一要做的工作就是创建一个新项目.我在 .NET 4.6 下调试了我的代码,修复了错误并切换回 Core.

The pragmatic solution I have found to get string.GetHashCode to return predicable values across multiple executions is simply to switch back to classic .NET (4.6). Since there is nothing .NET Core specific about my code, the only work I had to do was create a new project. I debugged my code under .NET 4.6, fixed the bug and switched back to Core.

这篇关于有没有办法使 .NET Core GetHashCode 具有确定性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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