C#随机字符串随机性不足的解決方式(随机数重复)

这个其实不是问题,一般情况下倒是不会出问题的,代码如下:

private string random_str(int length)
{

int number;
string checkCode = String.Empty;
int iSeed = 10;
Random ro = new Random(10);
long tick = DateTime.Now.Ticks;
Random random = new Random((int)(tick & 0xffffffffL) | (int)(tick >> 32));
for (int i = 0; i < length; i++)
{
number = random.Next();
number = number % 36;
if (number < 10)
{
number += 48;
}
else
{
number += 55;
}
checkCode += ((char)number).ToString();
}
return checkCode;
}

但是如果你蛋疼一下出现这种情况就不行了

random_str(4)+random_str(4)+random_str(4)

 

你会发新生成的12个字符其实是3个相同的字符串,于是心里面无数个草泥马奔腾而过。

其实稍微加个sleep就能解决这个问题:

 

private string random_str(int length)
{
System.Threading.Thread.Sleep(1);
int number;
string checkCode = String.Empty;
int iSeed = 10;
Random ro = new Random(10);
long tick = DateTime.Now.Ticks;
Random random = new Random((int)(tick & 0xffffffffL) | (int)(tick >> 32));
for (int i = 0; i < length; i++)
{
number = random.Next();
number = number % 36;
if (number < 10)
{
number += 48;
}
else
{
number += 55;
}
checkCode += ((char)number).ToString();
}
return checkCode;
}

本质上更接近真实的随机

posted @ 2013-02-18 22:03  MaxIE  阅读(947)  评论(0编辑  收藏  举报