c# - .NET 的 GUID 结构

标签 c# .net algorithm guid probability

http://msdn.microsoft.com/en-us/library/system.guid.aspx

它是如何工作的?它如何保证唯一ID?是只靠概率还是另有套路?我能否始终相信它会提供唯一 ID,或者在什么情况下我应该避免使用 guid?

最佳答案

这是一个有趣的小程序:

class Program
{
    static void Main(string[] args)
    {
        var guids = new HashSet<string>();
        var sw = Stopwatch.StartNew();

        while(true)
        {
            var guid = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 16);
            if (guids.Contains(guid)) break;
            guids.Add(guid);
        }

        Console.WriteLine("Duplicate found in {0} ms, after {1} items.", sw.ElapsedMilliseconds, guids.Count);
        Console.ReadLine();
    }
}

我打赌你会在它找到一个骗局之前耗尽内存;)

编辑:即使只使用半个 Guid。

关于c# - .NET 的 GUID 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4311522/

相关文章:

java - 是否可以在类本身中使实例为空?

c# - 如何使用 TextBox 对列表框中的所有数字求和?

c# - 如何通过代码设置 Crystal 报表的准确长度?

javascript - 部署时为 "That assembly does not allow partially trusted callers"

php - 根据变量值回显文本

任何地方的 C# Winforms ListView DoubleClick 事件

c# - 如何使用 IEnumerator.Reset()?

.net - 如何在gridview中组合下拉列表和空字段?

algorithm - 将数组的所有元素复制到指定索引处的另一个数组

algorithm - 如何通过结构光中的相移获得亚像素精度?