using System; using System.Collections.Generic; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { int len=8; Program p = new Program(); Console.WriteLine(p.RadomMumber(len)); Console.WriteLine("/n"); } public string RadomMumber(int len) { string str = "0,1,2,3,4,5,6,7,8,9,"; str += "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[] S = str.Split(new char[] { ',' });//将字符串拆分成字符串数组 string strNum = ""; int tag = -1;//用于记录一个随机数的值,避免产生两个重复的值 int i; Random rnd = new Random(); //产生一个长度为了len的随机字符串 for (i = 1; i <= len;i++) { if (tag == -1) { rnd = new Random(i * tag * unchecked((int)DateTime.Now.Ticks));//初始化一个实例 } int rndNum = rnd.Next(36);//返回小于61的随机数 //加入生成相同的数则重新生成。 if (tag != -1&&tag==rndNum) { return RadomMumber(1); } tag = rndNum; strNum += S[rndNum]; } return strNum; } } }
一个生成随机数的例子: