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;
        }
  

  

猜你喜欢

转载自www.cnblogs.com/xq-1209/p/10210576.html