增量的Guid在C# [英] Increment Guid in C#

查看:233
本文介绍了增量的Guid在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有必须是唯一的(当然)一个GUID变量的应用程序。我知道有统计学任何GUID应该只被假定为唯一的,但由于开发/测试环境的原因,相同的值可以看出多次。出现这种情况,所以当我想增量的GUID的价值,而不是仅仅创造了一个全新的。似乎没有成为一个简单的方法来做到这一点。我发现一个黑客,我将发布作为一个可能的答案,但希望有一个更清洁的解决方案。

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/test environment reasons, the same value may be seen multiple times. So when that happens, I want to "increment" the value of the Guid, rather than just creating a whole new one. There does not seem to be a simple way to do this. I found a hack, which I will post as a possible answer, but want a cleaner solution.

推荐答案

您可以得到字节GUID的组成部分,所以你可以说只是工作:

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);
    }
}



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

now with correct byte order

这篇关于增量的Guid在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆