随机字符串代 - 两个生成了一个又一个给出相同的结果 [英] random string generation - two generated one after another give same results
问题描述
我有一段简单的代码:
public string GenerateRandomString()
{
string randomString = string.Empty;
Random r = new Random();
for (int i = 0; i < length; i++)
randomString += chars[r.Next(chars.Length)];
return randomString;
}
如果我调用这个函数来生成两个字符串,一个接一个,他们是相同的......但是,如果我通过在产生串两线调试 - 的结果是不同的。
没有人知道为什么会发生?
If i call this function to generate two strings, one after another, they are identical... but if i debug through the two lines where the strings are generated - the results are different. does anyone know why is it happening?
推荐答案
这正在发生,因为调用发生非常接近对方(在同一毫秒),然后随机构造函数将播种随机对象,相同的值(它使用日期和放大器;默认时间)。
This is happening, because the calls happen very close to each other (during the same milli-second), then the Random constructor will seed the Random object with the same value (it uses date & time by default).
所以,有两种解决办法,其实。
So, there are two solutions, actually.
1。提供自己的种子值,这将是唯一在构造Random对象每次。
1. Provide your own seed value, that would be unique each time you construct the Random object.
2。始终使用相同的随机对象 - 只构建一次
就个人而言,我会使用第二种方法。它可以通过使Random对象静态的,或使之类的构件来进行。
Personally, I would use the second approach. It can be done by making the Random object static, or making it a member of the class.
这篇关于随机字符串代 - 两个生成了一个又一个给出相同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!