当前位置: 代码迷 >> C# >> Winform拖6个lable随机数重复,该怎么解决
  详细解决方案

Winform拖6个lable随机数重复,该怎么解决

热度:320   发布时间:2016-05-05 05:04:29.0
Winform拖6个lable随机数重复
代码如下:每次都生成重复的6个随机数,方法没问题,每次Debug会变化,但F5直接运行都是重复的
 private char[] charArray = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
private void Form1_Load(object sender, EventArgs e)
        {
            ClearLable();
            CreateQuestions();
        }

 public void ClearLable() 
        {
            this.lblQuestion1.Text = string.Empty;
            this.lblQuestion2.Text = string.Empty;
            this.lblQuestion3.Text = string.Empty;
            this.lblQuestion4.Text = string.Empty;
            this.lblQuestion5.Text = string.Empty;
            this.lblQuestion6.Text = string.Empty;
            this.lblMessage.Text = string.Empty;
        }
public void CreateQuestions()
        {
            string key = "lblQuestion";
            for (int i = 1; i <= 6;i++ )
            {
                Label lbl = this.Controls[key+i] as Label;
                lbl.Text = GetRandomChar();
            }
        }
public string GetRandomChar()
        {
            Random rd = new Random();
            int index = rd.Next(1, 26);
            return charArray[index].ToString();
        }
------解决思路----------------------
函数中random 变量多次new,而构造函数默认以世界为种子,在短时间内,种子不变、random出的随机数就一样了
------解决思路----------------------
Random rd = new Random();放到循环外面
------解决思路----------------------
如果你知道随机数的产生原理,就不会对这个问题很惊讶了
随机数说白了其实并不随机,它是根据当前的时间片来计算的
对人来说,当前的时间实在变化的太快,所以用当前时间作为随机数的第一个初始参数就可以实现伪"随机"

而获取了第一个随机数之后,之后的随机数则是将之前得到的随机数一起代入计算,保证获取到的数尽量离散少重复

而你在同一时间多次new了Random,这个初始化的,第一次生成的随机数,必然都是一样的
------解决思路----------------------
一般来说,你进需要初始化一次随机数发生器:
public static Random rd = new Random();

然后各个过程中共用它。
------解决思路----------------------
public static readonly Random rd = new Random();

------解决思路----------------------
使用年月日时分秒来作为随机的种子。
  相关解决方案