Guid.NewGuid 方法

定义

初始化 Guid 结构的新实例。

public:
 static Guid NewGuid();
public static Guid NewGuid ();
static member NewGuid : unit -> Guid
Public Shared Function NewGuid () As Guid

返回

一个新的 GUID 对象。

示例

下面的代码示例创建并显示两 Guid 个 对象的值。

// Create and display the value of two GUIDs.
Guid g = Guid.NewGuid();
Console.WriteLine(g);
Console.WriteLine(Guid.NewGuid());

// This code example produces a result similar to the following:

// 0f8fad5b-d9cb-469f-a165-70867728950e
// 7c9e6679-7425-40de-944b-e07fc1f90ae7
open System

// Create and display the value of two GUIDs.
let g = Guid.NewGuid()
printfn $"{g}"
printfn $"{Guid.NewGuid()}"

// This code example produces a result similar to the following:
//     0f8fad5b-d9cb-469f-a165-70867728950e
//     7c9e6679-7425-40de-944b-e07fc1f90ae7
' This code example demonstrates the Guid.NewGuid() method.
Class Sample
    Public Shared Sub Main()
        Dim g As Guid
        ' Create and display the value of two GUIDs.
        g = Guid.NewGuid()
        Console.WriteLine(g)
        Console.WriteLine(Guid.NewGuid())
    End Sub
End Class
'
'This code example produces the following results:
'
'0f8fad5b-d9cb-469f-a165-70867728950e
'7c9e6679-7425-40de-944b-e07fc1f90ae7
'

注解

这是一个方便 static 的方法,你可以调用它来获取新的 Guid。 方法创建版本 4 通用唯一标识符 (UUID) ,如 RFC 4122,第 4.4 节中所述。 返回的 Guid 保证不等于 Guid.Empty

在 Windows 上,此函数包装对 CoCreateGuid 函数的 调用。 生成的 GUID 包含 122 位强熵。

在非 Windows 平台上,从 .NET 6 开始,此函数调用 OS 的基础加密安全伪随机数生成器 (CSPRNG) 生成 122 位强熵。 在早期版本的 .NET 中,不能保证 CSPRNG 会生成熵。

建议应用程序 不要NewGuid 方法用于加密目的。 首先,由于版本 4 UUID 具有部分可预测的位模式, 因此 NewGuid 函数不能用作正确的加密伪随机函数 (PRF) 。 如果将 NewGuid 的输出提供给要求其输入由适当的 PRF 生成的加密组件,则加密组件可能无法维护其安全属性。 其次,无论平台如何, NewGuid 最多利用 122 位的熵。 某些加密组件根据策略对其输入设置最小熵级别。 此类策略通常将最小熵级别设置为 128 位或更高。 将 NewGuid 的输出传递给此类例程可能会违反其策略。

如果应用程序需要用于加密目的的随机数据,请考虑对 RandomNumberGenerator 类使用静态方法。 该类提供适用于加密的随机数生成器。

适用于