Increment Guid in C#

后端 未结 4 782
一向
一向 2021-01-17 18:32

I have an application that has a guid variable which needs to be unique (of course). I know that statistically any guid should just be assumed to be unique, but due to dev/t

4条回答
  •  轮回少年
    2021-01-17 18:37

    You can get the byte components of the guid, so you can just work on that:

    static class GuidExtensions
    {
        private static readonly int[] _guidByteOrder =
            new[] { 15, 14, 13, 12, 11, 10, 9, 8, 6, 7, 4, 5, 0, 1, 2, 3 };
        public static Guid Increment(this Guid guid)
        {
            var bytes = guid.ToByteArray();
            bool carry = true;
            for (int i = 0; i < _guidByteOrder.Length && carry; i++)
            {
                int index = _guidByteOrder[i];
                byte oldValue = bytes[index]++;
                carry = oldValue > bytes[index];
            }
            return new Guid(bytes);
        }
    }
    

    EDIT: now with correct byte order

提交回复
热议问题