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,Sec. 4.4 中所述。 Guid返回的保证不相等Guid.Empty

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

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

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

如果应用程序需要随机数据进行加密,请考虑在 RandomNumberGenerator 类上使用静态方法。 该类提供一个适合加密使用的随机数生成器。

适用于