public string GetRandomStr(int digit)
{
System.Random RndCls = new System.Random(unchecked((int) DateTime.Now.Ticks));
string s = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string RndStr = "";
for (int i = 1; i <= digit; i++)
{
RndStr += s.Substring(RndCls.Next(0, s.Length - 1), 1);
};
return RndStr;
}
假如是五位随机数,概率是1/[(26+10+26)^5]=1/(62^5)=1/916132832,小得够可怜啦,基本应用够了,如果不够再加一些特殊的字符,呵呵~~~{
System.Random RndCls = new System.Random(unchecked((int) DateTime.Now.Ticks));
string s = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string RndStr = "";
for (int i = 1; i <= digit; i++)
{
RndStr += s.Substring(RndCls.Next(0, s.Length - 1), 1);
};
return RndStr;
}
由于现在的计算机速度超级快,这个方法在循环中使用会得到相同的随机数,解决的办法是取随机数时候加入:
System.Threading.Thread.Sleep(50); //50表示0.05秒,可依据计算机速度修改这个值,争取最小;
string u = DateTime.Now.ToString("yy-MM-dd-hh-mm-ss") + DateTime.Now.Millisecond.ToString(); //这个取时间,可配合随机数用,但长度增加~~~
// 函 数 : getrandnum
// 作 用 : 获取一个随机数
// 返 回 值 : int,指定范围的一个随机数
// 参数(int) : 无 参 数,返回0-2147483647范围内的一个随机数
// 一个参数 : 返回0-参数之间的一个随机数
// 两个参数 : 返回两个参数之间的一个随机数
static int getrandnum(params int[] digital)
{
Random ro = new Random();
int startnum, endnum;
if (digital.Length == 0)
{
startnum = 0;
endnum = 2147483647;
}
else if (digital.Length == 1)
{
startnum = 0;
endnum = digital[0];
}
else
{
startnum = digital[0];
endnum = digital[1];
}
return ro.Next(startnum, endnum);
}
// 作 用 : 获取一个随机数
// 返 回 值 : int,指定范围的一个随机数
// 参数(int) : 无 参 数,返回0-2147483647范围内的一个随机数
// 一个参数 : 返回0-参数之间的一个随机数
// 两个参数 : 返回两个参数之间的一个随机数
static int getrandnum(params int[] digital)
{
Random ro = new Random();
int startnum, endnum;
if (digital.Length == 0)
{
startnum = 0;
endnum = 2147483647;
}
else if (digital.Length == 1)
{
startnum = 0;
endnum = digital[0];
}
else
{
startnum = digital[0];
endnum = digital[1];
}
return ro.Next(startnum, endnum);
}
public static int[] getRandomArray(int count)
{
int[] intArray = new int[count];
ArrayList newArray = new ArrayList();
Random rnd = new Random(unchecked((int) DateTime.Now.Ticks));
while (newArray.Count < count)
{
int tempNumber = rnd.Next(1, count+1);
if (!newArray.Contains(tempNumber))
newArray.Add(tempNumber);
}
for (int i = 0; i < count; i++)
{
intArray[i] = (int)newArray[i];
}
return intArray;
}