增加C#中的Guid

Aba*_*cus 9 c# guid increment

我有一个具有guid变量的应用程序,该变量需要是唯一的(当然).我知道统计上任何guid应该被认为是唯一的,但由于开发/测试环境的原因,可以多次看到相同的值.所以当发生这种情况时,我想"增加"Guid的值,而不是仅仅创建一个全新的值.似乎没有一种简单的方法可以做到这一点.我找到了一个黑客,我将作为一个可能的答案发布,但想要一个更清洁的解决方案.

Tho*_*que 13

你可以得到guid的字节组件,所以你可以解决这个问题:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:现在正确的字节顺序


Raw*_*ing 8

感谢Thomas Levesque的字节顺序,这里有一个漂亮的LINQ实现:

static int[] byteOrder = { 15, 14, 13, 12, 11, 10, 9, 8, 6, 7, 4, 5, 0, 1, 2, 3 };

static Guid NextGuid(Guid guid)
{
    var bytes = guid.ToByteArray();
    var canIncrement = byteOrder.Any(i => ++bytes[i] != 0);
    return new Guid(canIncrement ? bytes : new byte[16]);
}
Run Code Online (Sandbox Code Playgroud)

请注意,Guid.Empty如果你设法将它增加到那么远,它就会被包围.

如果你继续增加一个副本bytes而不是ToByteArray依次调用每个GUID,效率会更高.