默认情况下,.NET的随机数是根据系统时间来生成的,如果电脑速度很快的话,生成的随机数就会一样。 Random rnd = new Random();
int rndNum = rnd.Next(); //int 取值范围内的随机数
int rndNum = rnd.Next(10); //得0~9的随机数
int rndNum = rnd.Next(10,20); //得10~19的随机数
int rndNum = rnd.NextDouble(); //得0~1的随机数 若随机种子为系统时间,用循环一次生成多个随机数.
因为CPU运算速度太快了,所以每次取到的都是同一个时间.即生成的数字都一样了.
所以要不停地变换种子. public string GetRandomCode()
{
char[] chars = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'M', 'N', 'P', 'Q', 'R', 'S',
'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9'
};
string code = string.Empty;
for (int i = 0; i < 4; i++)
{
//这里是关键,传入一个seed参数即可保证生成的随机数不同
//Random rnd = new Random(unchecked((int)DateTime.Now.Ticks));
Random rnd = new Random(GetRandomSeed( ));
code += chars[rnd.Next(0, 30)].ToString();
}
return code;
}
static int GetRandomSeed( )
{
byte[] bytes = new byte[4];
System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider( );
rng.GetBytes( bytes );
return BitConverter.ToInt32( bytes , 0 );
}