public static class API
{
/// <summary>
/// 创建有序的 guid。
/// </summary>
/// <returns></returns>
public static Guid NewSequentialGuid()
{
Guid result;
UuidCreateSequential(out result);
return result;
}
/// <summary>
/// http://stackoverflow.com/questions/211498/is-there-a-net-equalent-to-sql-servers-newsequentialid
/// </summary>
/// <param name="guid"></param>
/// <returns></returns>
[DllImport("rpcrt4.dll", SetLastError = true)]
private static extern int UuidCreateSequential(out Guid guid);
[Obsolete("这个不是有序的,测试未通过。")]
/// <summary>
/// http://snipplr.com/view.php?codeview&id=29304
/// </summary>
/// <returns></returns>
public static Guid NewComb()
{
byte[] dateBytes = BitConverter.GetBytes(DateTime.Now.Ticks);
byte[] guidBytes = Guid.NewGuid().ToByteArray();
// copy the last six bytes from the date to the last six bytes of the GUID
Array.Copy(dateBytes, dateBytes.Length - 7, guidBytes, guidBytes.Length - 7, 6);
return new Guid(guidBytes);
}
}
测试
[TestFixture]
public class APITest
{
[Test]
public void testUuidCreateSequential()
{
List<Guid> list = new List<Guid>();
for (int i = 0; i < 100; i++)
{
Guid id = API.NewSequentialGuid();
list.Add(id);
Console.WriteLine(id);
}
for (int i = 0; i < list.Count - 1; i++)
{
Assert.Less(list[i], list[i + 1]);
}
}
[Test]
public void testNewComb()
{
List<Guid> list = new List<Guid>();
for (int i = 0; i < 100; i++)
{
Guid id = API.NewComb();
list.Add(id);
Console.WriteLine(id);
}
for (int i = 0; i < list.Count - 1; i++)
{
Assert.Less(list[i], list[i + 1]);
}
}
}