復制代碼 代碼如下:
/// <summary>
/// 返回隨機數
/// </summary>
/// <param name="VcodeNum"></param>
/// <returns></returns>
public string RndNum(int VcodeNum)
{
string Vchar = "0,1,2,3,4,5,6,7,8,9";
string[] VcArray = Vchar.Split(',');
string VNum = "";//由於字符串很短,就不用StringBuilder了
int temp = -1;//記錄上次隨機數值,盡量避免生產幾個一樣的隨機數
//采用一個簡單的算法以保證生成隨機數的不同
Random rand = new Random();
for (int i = 1; i < VcodeNum + 1; i++)
{
if (temp != -1)
{
rand = new Random(i * temp * unchecked((int)DateTime.Now.Ticks));
}
//int t = rand.Next(35) ;
int t = rand.Next(9);
if (temp != -1 && temp == t)
{
return RndNum(VcodeNum);
}
temp = t;
VNum += VcArray[t];
}
return VNum;
}
調用時只需要 string code = RndNum(4);
這樣取得了4位隨機數.
如果需要字母隨機數,則
string Vchar = "0,1,2,3,4,5,6,7,8,9,A,B";把字母加上去.
同時修改int t = rand.Next(9);中的9改成Vchar的長度但可.