生活随笔
收集整理的這篇文章主要介紹了
随机数生成器
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
public static class RandomHelper
{
/// <summary>
/// 隨機(jī)數(shù)生成器
/// </summary>
public static Random Generator { get; } = new Random(SystemRandomInt());
/// <summary>
/// 使用RNGCryptoServiceProvider生成真正隨機(jī)的二進(jìn)制數(shù)據(jù)
/// </summary>
public static byte[] SystemRandomBytes()
{
byte[] bytes = System.Guid.NewGuid().ToByteArray();
return bytes;
}
/// <summary>
/// 使用RNGCryptoServiceProvider生成真正隨機(jī)的整數(shù)
/// </summary>
public static int SystemRandomInt()
{
return BitConverter.ToInt32(SystemRandomBytes(), 0);
}
/// <summary>
/// 生成10位數(shù)的編號
/// </summary>
public static string GenerateSerial()
{
//把guid轉(zhuǎn)換為兩個long int
byte[] bytes = System.Guid.NewGuid().ToByteArray();
UInt64 high = System.BitConverter.ToUInt64(bytes, 0);
UInt64 low = System.BitConverter.ToUInt64(bytes, 8);
//轉(zhuǎn)換為10位數(shù)字
UInt64 mixed = ((high ^ low) % 8999999999) + 1000000000;
return mixed.ToString();
}
public static string GenerateOrderId()
{
long id = DateTime.Now.Ticks - DateTime.Parse("2017/01/01").Ticks;
return id.ToString("D10");
}
/// <summary>
/// 生成隨機(jī)字符串
/// </summary>
/// <param name="length">字符串長度</param>
/// <param name="chars">包含的字符,默認(rèn)是a-zA-Z0-9</param>
/// <returns></returns>
public static string RandomString(int length, string chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
{
var buffer = new char[length];
for (int n = 0; n < length; ++n)
{
buffer[n] = chars[Generator.Next(chars.Length)];
}
return new string(buffer);
}
}
總結(jié)
以上是生活随笔為你收集整理的随机数生成器的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。