【发布时间】:2021-06-17 03:11:51
【问题描述】:
我需要我的应用程序处理来自数据库的模组列表和本地下载的模组列表。
数据库的每个模组都有一个唯一的uint ID,我用它来识别他,但本地模组没有任何 ID。
起初我尝试使用模组的名称生成带有string.GetHashCode() 的 ID,但 GetHashCode 在应用程序的每次运行时仍然是随机的。
有没有其他方法可以从 mod 的名称生成一个持久的 uint ID ?
当前代码:
foreach(string mod in localMods)
{
//This way I get a number between 0 and 2147483648
uint newId = Convert.ToUInt32(Math.Abs(mod.GetHashCode());
ProfileMod newMod = new ProfileMod(newId);
}
【问题讨论】:
-
使用任何你喜欢的散列函数(MD5 等)。但请注意,可能会发生碰撞。
-
"GetHashCode 在每次运行应用程序时仍然是随机的" .不,那你基本上有一个严重的代码问题。 HashCodes 不应在应用程序运行之间更改。
-
@TomTom 实际上,
object.GetHashCode()的文档明确指出In some cases, hash codes may be computed on a per-process or per-application domain basis.因此调用object.GetHashCode()返回的值很可能在运行之间发生变化。 -
碰撞应该不是真正的问题,因为它只处理少量的模组,甚至更少量的本地模组。 @TomTom 我也是这么想的......我使用的是
Convert.ToUInt32(Math.Abs(mod.GetHashCode()),在两次运行之间,有时会有所不同 -
在您的
mod.GetHashCode()示例中,mod的类型是什么?string.GetHashCode()通常确实在运行之间返回相同的值(但不能保证这样做,你绝不能依赖它)