我有一个应用程序有一个 guid 变量,它需要是唯一的(当然)。我知道从统计学上讲,任何 guid 都应该被假定为唯一的,但是由于开发/测试环境的原因,可能会多次看到相同的值。因此,当发生这种情况时,我想“增加”Guid 的值(value),而不是仅仅创建一个全新的。似乎没有一种简单的方法可以做到这一点。我发现了一个 hack,我将把它作为可能的答案发布,但我想要一个更简洁的解决方案。
最佳答案
您可以获得 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);
}
}
编辑:现在有正确的字节顺序
关于c# - C# 中的增量 Guid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30404965/