到目前为止我收集到的信息是,哈希码是整数,有助于更快地从数组中查找数据。看这段代码:
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 的哈希码不断变化,即使字符串没有改变。哈希码到底是什么以及它们是如何生成的(如果需要)?