你也可以在c#上生成你的id,看看这个关于代码项目的帖子prb是这个实现生成的代码与NEWSEQUENTIALID生成的不匹配,因为我的目标是c#代码会生成最后6个Guid 的字节作为 Sql 服务器的 NewSequentialID 函数,我最终得到以下代码。
public static Guid ToSequentialAtEnd(this Guid guid)
{
byte[] guidArray = guid.ToByteArray();
DateTime now = DateTime.UtcNow;
var baseDate = new DateTime(1900, 1, 1);
// Get the days and milliseconds which will be used to build the byte string
var days = new TimeSpan(now.Ticks - baseDate.Ticks);
TimeSpan msecs = now.TimeOfDay;
// Convert to a byte array
// Note that SQL Server is accurate to 1/300th of a millisecond so we divide by 3.33333333
byte[] daysArray = BitConverter.GetBytes(days.Days);
byte[] msecsArray = BitConverter.GetBytes((long)(msecs.TotalMilliseconds / 3.33333333));
// Reverse the bytes to match SQL Servers ordering
Array.Reverse(daysArray);
Array.Reverse(msecsArray);
// Copy the bytes into the guid
Array.Copy(daysArray, daysArray.Length - 2, guidArray, guidArray.Length - 6, 2);
Array.Copy(msecsArray, msecsArray.Length - 4, guidArray, guidArray.Length - 4, 4);
return new Guid(guidArray);
}