当多次调用时,生成的随机字符串不是随机的

Kir*_*irk 3 c# asp.net

我正在尝试创建一个随机生成的单词串,除非我连续多次调用它,否则它可以正常工作.这是在WebForms页面上,单词列表来自文件.

我怀疑我不理解C#中的某些东西,或者在这种情况下ASP.NET可能工作,有人可以解释为什么会发生这种情况以及如何解决问题吗?

这是方法

public string GeneratePhrase()
{
    // get dictionary file
    var data = File.ReadAllLines(HttpContext.Current.Server.MapPath("~/libs/words.txt"));

    Random rand = new Random();
    int r1 = rand.Next(data.Count());
    int r2 = rand.Next(data.Count());
    int r3 = rand.Next(data.Count());

    string p1 = data.ElementAt(r1).ToLower();
    string p2 = data.ElementAt(r2).ToLower();
    string p3 = data.ElementAt(r3).ToLower();

    string ret = string.Format("{0}{1}{2}", p1, p2, p3);
    return ret;
}
Run Code Online (Sandbox Code Playgroud)

如果我在a期间调用一次PostBack,那就很好并且总是创建一个随机的单词组合.但是如果我在PostBack期间多次使用它,它只是从每次调用重复相同的随机字符串.

string s1 = this.GeneratePhrase();
string s2 = this.GeneratePhrase();
string s3 = this.GeneratePhrase();
Response.Write(s1);
Response.Write(s2);
Response.Write(s3);
Run Code Online (Sandbox Code Playgroud)

产量

tirefriendhotdog
tirefriendhotdog
tirefriendhotdog
Run Code Online (Sandbox Code Playgroud)

为何会出现这种情况的原因?

D S*_*ley 6

Random rand = new Random();使用当前时间作为种子值,因此快速连续多次调用它将为您提供相同的随机序列.您可以:

  • 创建一个Random用于所有请求的单个对象
  • 用不同的伪随机数播种它 Guid.NewGuid().GetHashCode()
  • 使用与时间无关的其他随机数生成器.