问一个连接随机码的问题,请高手帮个忙?
我现在要生成多个8位的随机码,是由数字和字母组成的。
现在生成一个没有问题,可是我要一次性生成几百个这样生成的数全是一样的。怎么样能不让它一样中。
比如我生成8个随机码,可是这8个全是1Q2WY67U,下面是我的代码
private string GenCode(int num)
{
string[] source={ "0 ", "1 ", "2 ", "3 ", "4 ", "5 ", "6 ", "7 ", "8 ", "9 ",
"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 "};
string code= " ";
Random rd=new Random();
for(int i=0;i < num;i++)
{
code += source[rd.Next(0,source.Length)];
}
return code;
}
下面的是调用
for(int j=0;j <8;j++)
{
string tmp = GenCode(8);
Response.Write(tmp);
}
------解决方案--------------------/// <summary>
/// 生成字母+数字随机数
/// </summary>
/// <param name= "length "> 长度 </param>
/// <returns> </returns>
public static string GetRandom(int length)
{
string result = " ";
string include = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ";
Random random = new Random();
for (int i = 0; i < length; i++)
{
result += include[random.Next(0, 35)].ToString();
}
return result;
}
------解决方案--------------------把Random 对象拿出来,可以做一个外层类 变量
Random rand =new Random();
public string GetCode(int num)
{
...
code += source[rd.Next(0,source.Length)];
...
}
多个Random实例的相似时间的调用结果不会散开的
------解决方案--------------------Random rd=new Random();
这句放在外边就可以了
private Random rd=new Random();
private string GenCode(int num)
{
string[] source={ "0 ", "1 ", "2 ", "3 ", "4 ", "5 ", "6 ", "7 ", "8 ", "9 ",