起因
最近一直在学习Abp框架相关的知识,在Abp文档上看到通过IGuidGenerator接口Create方法实现的GUID是连续的.便想看看内部是如何实现的.
Create源码(裁剪部分代码)
var random = RandomNumberGenerator.Create();
var randomBytes = new byte[10];
random.GetBytes(randomBytes);
long timestamp = DateTime.UtcNow.Ticks / 10000L;
byte[] timestampBytes = BitConverter.GetBytes(timestamp);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(timestampBytes);
}
byte[] guidBytes = new byte[16];
Buffer.BlockCopy(randomBytes, 0, guidBytes, 0, 10);
Buffer.BlockCopy(timestampBytes, 2, guidBytes, 10, 6);
var guid = new Guid(guidBytes);
Console.WriteLine(guid.ToString());
看到上面的代码,可以简单的分为一下几个步骤:
1. 创建一个长度为10的byte数组,存放随机数.
2. 获取当前时间的毫秒数
3. 判断是否为小端,如果为小端,则把时间的毫秒数进行反转
4. 创建长度为16的byte,将随机数拷贝该数组,然后将时间毫秒数也拷贝到该数组中
5. 通过Guid的构造函数,传入长度16的数组,进行生成连续的Guid