了解 .NET 中的哈希代码

Ixc*_*n35 -5 .net c# random hash hashcode

到目前为止我收集到的信息是,哈希码是整数,有助于更快地从数组中查找数据。看这段代码:

string x = "Run the program to find this string's hash code!";
int hashCode = x.GetHashCode();
Random random = new Random(hashCode);

for(int i = 0; i<100; i++)
{
// Always generates the same set of random integers 60, 23, 67, 80, 89, 44, 44 and so on...
int randomNumber = random.Next(0, 100);

Console.WriteLine("Hash Code is: {0}", hashCode);
Console.WriteLine("The random number it generates is: {0}", randomNumber);

Console.ReadKey();
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我使用字符串的哈希码x作为随机数生成器的种子。这段代码给了我 100 个随机整数,但每次运行该程序时,它都会给我相同的随机数集!我的问题是:为什么每次循环迭代时它都会给我一个不同的随机数?为什么 x 的哈希码不断变化,即使字符串没有改变。哈希码到底是什么以及它们是如何生成的(如果需要)?

Ser*_*rvy 5

对于给定对象来说,在程序执行的整个生命周期中哈希码保持不变至关重要。不应依赖给定对象的哈希码在程序的多次执行中保持不变,而这正是您正在做的事情。许多实现在不同的程序调用中会碰巧保持相同,但 .NETstring实现却不然。