最近,因工作需要生成一个不重复的随机字符串,园子里查了没有找到合适的。找了其他的作为参考并修改了下,记录一下。
/// <summary>
/// 可用字符
/// </summary>
static char[] sc;
/// <summary>
/// 起始时间
/// </summary>
static DateTime startTime;
/// <summary>
/// 字符串前缀
/// </summary>
static long prve = 0;
/// <summary>
/// 位数设置
/// </summary>
static int len = 0;
/// <summary>
/// 锁
/// </summary>
static readonly object _lock = new object();
/// <summary> /// 创建一个在本地唯一的短字符串生成对象 /// </summary> public MyConsoleDemoModule() { if (sc == null) { //根据需求可加入小写abcdefghijklmnopqrstuvwxyz sc = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray(); //起始时间越大,时间戳就越小,字符串才能越短 startTime = new DateTime(2024, 10, 12, 0, 0, 0, 0); //位数设置 len = 8; } }
生成方法:
/// <summary> /// 生成一个唯一的短字符串 /// </summary> public string Create() { lock (_lock) { //使用时间戳确保不会重复 TimeSpan ts = DateTime.UtcNow - startTime; //毫秒1000*10,每秒自增(0-9999) long tempSeconds = Convert.ToInt64(ts.TotalMilliseconds * 10); //防重复冗余设置(前缀自增,未超过当前时间戳就用) prve = tempSeconds > prve ? tempSeconds : prve++; //获取字符串 return GetShortString(prve, len); } }
字符串处理:
/// <summary> /// 使用进制生成短字符串 /// </summary> /// <param name="num">毫秒自增时间戳</param> /// <param name="len">位数设置</param> /// <returns></returns> private string GetShortString(long num, int len) { var str = ""; while (num >= sc.Length) { //取余赋值 str = sc[num % sc.Length] + str; num = num / sc.Length; } var ret = sc[num] + str; if (ret.Length > len) { return ret.Substring(0, len); } else { var pre = string.Empty; for (int x = 0; x < len - ret.Length; x++) { Random random = new Random(); //随机取字符串数组字符 var index = random.Next(0, (sc.Length - 1)); //累加字符串 pre += sc[index]; } //拼接 return pre + ret; } }
调用,查看结果
标签:C#,len,sc,Length,num,static,字符串,重复 From: https://www.cnblogs.com/youyoufei/p/18469486