C#函数:获取自定义GUID c#常用获取类型的方法有哪些?
代码如下:
private readonly ThreadLocal<Random> random = new ThreadLocal<Random>(() => new Random());
private void button1_Click(object sender, EventArgs e)
{
TryIt();
}
string GenerateGUID()
{
string currentDate = DateTime.Now.ToString("yyyyMMdd");
string currentTime = DateTime.Now.ToString("HHmmss");
string milliseconds = DateTime.Now.ToString("fff"); // 毫秒
string GUID = currentDate + "-" + currentTime + "-" +
milliseconds + "-" + CreateRandomHex(3) + "-" +
CreateRandomHex(12);
return GUID.ToUpper();
}
string CreateRandomHex(int length)
{
const string hexChars = "0123456789ABCDEF";
StringBuilder hexString = new StringBuilder();
using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
{
byte[] randomBytes = new byte[length];
rng.GetBytes(randomBytes);
for (int i = 0; i < length; i++)
{
int index = randomBytes[i] % hexChars.Length;
hexString.Append(hexChars[index]);
}
}
return hexString.ToString();
}
void TryIt()
{
for (int i = 0; i < 1000; i++)
{
string newGUID = GenerateGUID();
Debug.WriteLine(newGUID);
}
}