c# - 9个字符的唯一随机字符串(用于单表)

标签 c# .net

我想生成一个 9 位数字的唯一随机字符串。目前我正在使用

Guid.NewGuid().ToString().Replace("-","").Substring(0,9)

但恐怕很快就会发生碰撞。有没有更好的方法,或者这样可以吗?

最佳答案

如果您采用 GUID 的子字符串 you are not guaranteed randomness uniqueness at all .

参见 my answer to a older SO question满足您的随机性要求。这是执行此操作的基本代码。

public static string CreateRandomString(int length)
{
    length -= 12; //12 digits are the counter
    if (length <= 0)
        throw new ArgumentOutOfRangeException("length");
    long count = System.Threading.Interlocked.Increment(ref counter);
    Byte[] randomBytes = new Byte[length * 3 / 4];
    RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
    rng.GetBytes(randomBytes);

    byte[] buf = new byte[8];
    buf[0] = (byte)count;
    buf[1] = (byte)(count >> 8);
    buf[2] = (byte)(count >> 16);
    buf[3] = (byte)(count >> 24);
    buf[4] = (byte)(count >> 32);
    buf[5] = (byte)(count >> 40);
    buf[6] = (byte)(count >> 48);
    buf[7] = (byte)(count >> 56);
    return Convert.ToBase64String(buf) + Convert.ToBase64String(randomBytes);
}

它为您提供 12 位计数以防止冲突以及您想要随机性的任何其他数字。您可以根据需要修改代码,使其短于 12 位数字字符串。

关于c# - 9个字符的唯一随机字符串(用于单表),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11981988/

相关文章:

c# - 为什么我的 List<string> 没有完全写在我的 .CSV 中?

c# - 反射:调用具有泛型参数的方法

c# - 在 .NET(或一般)中创建文档的正确方法是什么?

c# - 如何确定我的 winform 在哪个监视器中?

c# - 适用于 WP7 的 XNA 高速平滑动画

C#解析JavaScript内容

c# - 使具有相同值的对象之间的 HashSet<MyType> 不同

.net - 使用具有 POCO 支持的 Entity Framework 4 实现 propertychanged 事件的最罕见和最有效的方法是什么?

c# - Windows 窗体中的数据库数据类型及其等效项

c# - 如何在 C# 中更改 PriorityQueue 中包含的元素的优先级