有没有一种方法可以使.NET Core GetHashCode具有确定性 [英] Is there a way to make .NET Core GetHashCode deterministic

查看:151
本文介绍了有没有一种方法可以使.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天全站免登陆