c# - 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包含更多重复的数字。为什么?
怎么了?
解决方案
推荐阅读
- json - 如何确定哪种类型(类/结构)正确存储 JSON 数据
- java - 用于在令牌上拆分数组的正则表达式
- python - 如何将 Scapy 中的数据写入 CSV 文件
- r - R传单中的嵌套标记
- android - 如何在协程中进行同步调用
- python - 自动化使用 python docx 更新 Header 和 Footer 更新
- ibm-cloud - 无法从 ibmiotin 中的设备接收数据
- python - 部署到 Google Cloud Functions 时如何处理密钥和凭据?
- ios - Firebase Analytics 的自定义指标和维度 - iOS
- c++ - 前向声明closesocket函数的问题