是.NET字符串哈希函数便携? [英] Is the .NET string hash function portable?

查看:167
本文介绍了是.NET字符串哈希函数便携?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  

可能重复:
  <一href="http://stackoverflow.com/questions/5154970/how-do-i-create-a-hash$c$c-in-net-c-for-a-string-that-is-safe-to-store-in-a">How我在.NET中创建一个哈希code(C#)的字符串,它是安全的存储在数据库中?

我用C#4.0并通过调用得到的字符串哈希:

 我的字符串.GetHash code()
 

此调用产生的code被存储到数据库中,以备将来使用。该散列code,以便找到串的一些子集,然后以相等的比较

问题是:

  1. 它是一个标准的哈希计算?我可能会认为这是 可以计算出在.NET 3.0或未来的.Net版本?相同的散列在不同的环境中,如C#
  2. 是否有可能来计算自己相同的散列函数通过写它的Java,PL / SQL,红宝石等?
  3. 我可以假设,今天产生的哈希值将是相同的明天 同样的环境?例如,当我关闭我的电脑, 再次运行该程序,或更改语言环境,或者一些其他的设置?
  4. 什么是便携性的限制呢?
  5. 在我知道我可以自己做,但也许一些便携性提供?
解决方案

从MSDN:

  

在GetHash code方法的默认实现不针对不同的对象,保证唯一的返回值。此外,.NET Framework不保证GetHash code方法的默认实现,它返回值将不同版本的.NET Framework中的相同。因此,这种方法的缺省的实现必须不能用作一个唯一的对象标识符散列目的

所以,不,你不能假设由 GetHash code 所产生的价值是稳定的。这不仅是理论上的,或者 - 我们已经看到了价值变动在过去

如果你想有一个稳定的哈希值,你就必须自己生成它。

Possible Duplicate:
How do I create a HashCode in .net (c#) for a string that is safe to store in a database?

I use C# 4.0 and gets the string hash by invoking:

"my string".GetHashCode()

Code generated by this call is stored into database to future use. This hash code is used to find some subset of strings and then to equal comparison.

Questions are:

  1. Is it a standardized hash calculation? May I assume that it is possible to calculate the same hash in different environments like C# in .Net 3.0 or future .Net editions?
  2. Is it possible to calculate the same hash function on yourself by writing it in Java, PL/SQL, Ruby, etc?
  3. Can I assume that hash generated today will be the same tomorrow in the same environment? For example when I shutdown my computer and run the program again, or change locale, or some other settings?
  4. What are the limits of portability?
  5. I know I can do it yourself, but maybe some kind of portability is provided?

解决方案

From MSDN:

The default implementation of the GetHashCode method does not guarantee unique return values for different objects. Furthermore, the .NET Framework does not guarantee the default implementation of the GetHashCode method, and the value it returns will be the same between different versions of the .NET Framework. Consequently, the default implementation of this method must not be used as a unique object identifier for hashing purposes.

So no, you cannot assume that the value produced by GetHashCode is stable. This isn't just theoretical, either - we've seen the value change in the past.

If you want a stable hash, you'll have to generate it yourself.

这篇关于是.NET字符串哈希函数便携?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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