C#简单的生成随机数
//拿一个8位数的随机数 string randomNumber=GetCode(8); public string GetCode(int length) { char[] chars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; string code = string.Empty; Random random = new Random(); for (int i = 0; i < length; i++) { code += chars[random.Next(chars.Length)]; } //验证随机数是否存在过(我这里用的是ORM框架,直接用sql到数据库查一遍也一样,主要用于过滤重复) var list= new testModel() { test_code = code }.GetList<testModel>() ?? new List<testModel>(); if (list.Count > 0) { return GetCode(length); } return code; }
/// <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(); }
/// <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(); }