-
C#教程之RandomId生成随机字符串详解实例
/*
* 名称:RandomId
* 功能:生成随机ID
* 作者:冰麟轻武
* 日期:2012年1月31日 03:36:28
* 版本:1.0
* 最后更新:2012年1月31日 03:36:28
*/
using System;
using System.Text;
namespace blqw
{
public sealed class RandomId : IFormattable
{
/// <summary> 1234567890qwertyuiopasdfghjklzxcvbnm1234567890QWERTYUIOPASDFGHJKLZXCVBNM
/// </summary>
public const string ALLWORDS = "1234567890qwertyuiopasdfghjklzxcvbnm1234567890QWERTYUIOPASDFGHJKLZXCVBNM";
/// <summary> 2345678wertyuiopasdfghjkzxcvbnm23456780QWERTYUPASDFGHJKLZXCVBNM
/// </summary>
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
/// <summary> 构造函数
/// </summary>
/// <param name="length">生成Id长度</param>
/// <param name="dict">随机字符字典,默认字典为0-9a-zA-Z</param>
public RandomId(int length, string dict = ALLWORDS)
: this(RandomId.ToFormat(length), dict)
{ }
/// <summary> 构造函数
/// </summary>
/// <param name="format">生成Id格式</param>
/// <param name="dict">随机字符字典,默认字典为0-9a-zA-Z</param>
public RandomId(string format, string dict = ALLWORDS)
{
_Dict = dict;
_Format = format;
_RMax = dict.Length;
}
/// <summary> 生成Id
/// </summary>
public string Create()
{
return string.Format(_Format, this);
}
/// <summary> 生成Id
/// </summary>
/// <param name="length">生成Id长度</param>
/// <param name="dict">随机字符字典,默认字典为0-9a-zA-Z</param>
public static string Create(int length, string dict = ALLWORDS)
{
return new RandomId(length, dict).Create();
}
/// <summary> 生成Id
/// </summary>
/// <param name="format">生成Id格式</param>
/// <param name="dict">随机字符字典,默认字典为0-9a-zA-Z</param>
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"));//使用指定字典生成特定格式的随机字符