• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
IQ.indexOf("EQ")
博客园    首页    新随笔    联系   管理    订阅  订阅

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

  

posted @ 2019-01-02 19:03  凉生初雨  阅读(1210)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3