C#-生成唯一的6位随机码

时间:2019-01-21 07:42:45

标签: c#

我在下面的课程中写道,要在数据库中生成唯一的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 包含更多重复的数字。为什么?

怎么了?

0 个答案:

没有答案