现在的位置: 首页 > 综合 > 正文

奇怪的 Random

2011年11月30日 ⁄ 综合 ⁄ 共 1482字 ⁄ 字号 评论关闭
本文转载自:http://i.aspx1.com/showtopic-1726.htm,没能解决问题,所以发在这里请教。
刚才有位同学 问了 我个问题,是关于random的,很是奇怪,我也很不解。希望明白的同学指点一下。
代码很简单,就是输出几个随机数,程序如下:

        protected void Button1_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < 5; i++)
            {
                Response.Write(RandPass() + "\n");
            }
        }
        private string RandPass()
        {
            Random rand = new Random();
            string password = "";
            string[] passArray = new string[] { "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", "*", "%", "$", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
            for (int i = 0; i < 10; i++)
            {
                int number = rand.Next(passArray.Length);
                password += passArray[number];
            }
            return password;
        }

这段代码执行后,输出的是 5组 相同的随机字符串,更奇怪的是,当给代码设置断点后,单步执行时,输出的竟是5组不同的随机数了。
单步执行 与 正常运行 输出的结果竟然不同!
个人认为,这可能是random的问题,将代码改成如下,就正常了。

  Random rand = new Random();
        protected void Button1_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < 5; i++)
            {
                Response.Write(RandPass() + "\n");
            }
        }
        private string RandPass()
        {
            string password = "";
            string[] passArray = new string[] { "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", "*", "%", "$", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
            for (int i = 0; i < 10; i++)
            {
                int number = rand.Next(passArray.Length);
                password += passArray[number];
            }
            return password;
        }

这其中的原因,我也不太明白,希望同学们指点。

本文转载自:http://i.aspx1.com/showtopic-1726.htm,没能解决问题,所以发在这里请教。

抱歉!评论已关闭.