复制代码 代码如下:
using System;
using System.Text;
namespace blqw
{
public sealed class RandomId : IFormattable
{
///
///
public const string ALLWORDS = "1234567890qwertyuiopasdfghjklzxcvbnm1234567890QWERTYUIOPASDFGHJKLZXCVBNM";
///
///
public const string SIMPLEWORDS = "2345678wertyuipasdfghjkzxcvbnm2345678WERTYUPASDFGHJKLZXCVBNM";
#region 私有对象
const string ONE = "{0}";
static RandomId _Rid = new RandomId(0);
readonly static Random _Rand = new Random();
static string ToFormat(int length)
{
StringBuilder sb = new StringBuilder(length * 3);
for (int i = 0; i < length; i++)
{
sb.Append(ONE);
}
return sb.ToString();
}
readonly string _Dict;
readonly int _RMax;
readonly string _Format;
#endregion
///
///
/// 生成Id长度
/// 随机字符字典,默认字典为0-9a-zA-Z
public RandomId(int length, string dict = ALLWORDS)
: this(RandomId.ToFormat(length), dict)
{ }
///
///
/// 生成Id格式
/// 随机字符字典,默认字典为0-9a-zA-Z
public RandomId(string format, string dict = ALLWORDS)
{
_Dict = dict;
_Format = format;
_RMax = dict.Length;
}
///
///
public string Create()
{
return string.Format(_Format, this);
}
///
///
/// 生成Id长度
/// 随机字符字典,默认字典为0-9a-zA-Z
public static string Create(int length, string dict = ALLWORDS)
{
return new RandomId(length, dict).Create();
}
///
///
/// 生成Id格式
/// 随机字符字典,默认字典为0-9a-zA-Z
public static string Create(string format, string dict = ALLWORDS)
{
return new RandomId(format, dict).Create();
}
#region IFormattable 成员
string IFormattable.ToString(string format, IFormatProvider formatProvider)
{
return _Dict[_Rand.Next(0, _RMax)].ToString();
}
#endregion
}
}
复制代码 代码如下:
Console.WriteLine(RandomId.Create(4));//使用默认字典生成4位随机字符串,默认字典中不包含l,1,O,0,q,9等容易混淆字符
Console.WriteLine(RandomId.Create(4, RandomId.ALLWORDS));//使用完整字典(0-9a-zA-Z),生成4位随机字符
Console.WriteLine(RandomId.Create(10, "多少级开发和贷款撒了花费大量时间好快理发店撒娇哦就开放了的撒酒阿克里福德就是卡看了就分开的世界里分开家里的事"));//使用指定中文字典,生成4位随机字符
Console.WriteLine(RandomId.Create("SN:{0}{0}{0}{0}-{0}{0}{0}-{0}{0}{0}.{0}{0}", "123456abcdef"));//使用指定字典生成特定格式的随机字符



