标签:stat length uid alt oar 随机数 ring letter derby
c#随机生成随机数,可以自定义随机生成字母和数字的个数
上面是生成8位随机数,4位数字和4位字母的例子,
代码如下:
class Program { static void Main(string[] args) { for (int i = 0; i < 10; i++) { string result = CreateRandom(4, 4); Console.WriteLine(result); } } /// <summary> /// 创建随机数 /// </summary> /// <param name="Letter">字母个数</param> /// <param name="num">数字个数</param> /// <returns></returns> public static string CreateRandom(int Letter, int num) { string result = CreateRandomLetter(Letter) + CreateRandomNum(num); var temp = result.OrderBy(x => Guid.NewGuid()).ToArray(); // 按一个随机值排序后组合成数组 return new string(temp); } /// <summary> /// 创建字母随机数 /// </summary> /// <param name="letter"></param> /// <returns></returns> private static string CreateRandomLetter(int letter) { string str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; StringBuilder sb = new StringBuilder(); for (int i = 0; i < letter; i++) { sb.Append(str[new Random(Guid.NewGuid().GetHashCode()).Next(0, str.Length - 1)]); } return sb.ToString(); } /// <summary> /// 创建数字随机数 /// </summary> /// <param name="num"></param> /// <returns></returns> private static string CreateRandomNum(int num) { string str = "0123456789"; StringBuilder sb = new StringBuilder(); for (int i = 0; i < num; i++) { sb.Append(str[new Random(Guid.NewGuid().GetHashCode()).Next(0, str.Length - 1)]); } return sb.ToString(); } }
标签:stat length uid alt oar 随机数 ring letter derby
原文地址:http://www.cnblogs.com/testsec/p/6095979.html