首页 > 解决方案 > C# - 生成唯一的 6 位随机码

问题描述

我写了下面的类来在数据库中生成一个唯一的 6 位随机代码:

public class RndCode
{
    public static string Generate(int ID, int Length = 5)
    {
        string allowedChars = "0123456789";
        char[] chars = new char[Length];
        string code = "";
        Random rd = new Random();

        for (int i = 0; i < Length; i++)
        {
           chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];
        }

        string VCode = new string(chars);
        using (DataBaseContext db = new DataBaseContext())
        {
            if (!db.Members.Any(o => o.ID == ID && o.Code == VCode))
            {
                code = VCode;
            }
            else
            {
                Generate(ID, Length);
            }
        }
        return code;
     }
 }

并在我的控制器中使用它:

int id = 250;
List<string> AllCodes = new List<string>();
for (int i = 0; i < 20 ; i++)
{
     var RandomCode = Service.RndCode.Generate(id, 6);

     AllCodes.Add(RandomCode);
}

AllCodes包含更多重复的数字。为什么?

怎么了?

标签: c#

解决方案


推荐阅读