您的位置:首页 > 编程语言 > ASP

asp.net生成N组指定位数随机数都一样的解决办法

2016-01-11 16:20 726 查看
最初的生成随机字符串的函数

/// <summary>
/// 随机生成指定长度的字符串(只包括数字)
/// </summary>
/// <param name="length">长度</param>
/// <returns></returns>
public static string RandNumStr(int length)
{
string str = "1234567890";
Random r = new Random();
string result = "";
for (int i = 0; i < length; i++)
{
int m = r.Next(0, str.Length);
string s = str.Substring(m, 1);
result += s;
}
return result;

}


前端调用:

<div><%=Lib.Common.RandNumStr(9) %></div>
<div><%=Lib.Common.RandNumStr(9) %></div>
<div><%=Lib.Common.RandNumStr(9) %></div>
<div><%=Lib.Common.RandNumStr(9) %></div>
<div><%=Lib.Common.RandNumStr(9) %></div>
<div><%=Lib.Common.RandNumStr(9) %></div>
<div><%=Lib.Common.RandNumStr(9) %></div>
<div><%=Lib.Common.RandNumStr(9) %></div>
<div><%=Lib.Common.RandNumStr(9) %></div>
<div><%=Lib.Common.RandNumStr(9) %></div>


这样生成出来的10个随机数会全部都一样。怎么办呢?

加断点一步一步调试后发现就不会存在全部一样的结果。这也就是说,我们应该在每次生成随机的时候,加一个阻塞。

那我们在for循环里加一个阻塞试试。

/// <summary>
/// 随机生成指定长度的字符串(只包括数字)
/// </summary>
/// <param name="length">长度</param>
/// <returns></returns>
public static string RandNumStr(int length)
{
string str = "1234567890";
Random r = new Random();
string result = "";
for (int i = 0; i < length; i++)
{
int m = r.Next(0, str.Length);
string s = str.Substring(m, 1);
result += s;
//加一个阻塞试试
Thread.Sleep(5);
}
return result;

}


加了Thread.Sleep(5)之后,一切问题搞定了,参数根据自己的情况来设置吧,我反正设置5就合适了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: