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 位的強式 Entropy。

在非 Windows 平臺上,從 .NET 6 開始,此函式會呼叫 OS 的基礎密碼編譯安全虛擬亂數產生器, (CSPRNG) 產生 122 位的強式 entropy。 在舊版 .NET 中,Entropy 不保證是由 CSPRNG 產生。

建議應用程式 不要 使用 NewGuid 方法進行密碼編譯。 首先,由於第 4 版 UUID 具有部分可預測的位模式, NewGuid 函式無法作為適當的密碼編譯虛擬隨機函式, (PRF) 。 如果將 NewGuid 的輸出提供給需要由適當 PRF 產生其輸入的密碼編譯元件,密碼編譯元件可能無法維護其安全性屬性。 其次,不論平臺為何, NewGuid 最多都會利用 122 位的 Entropy。 有些密碼編譯元件會在其輸入上設定最小 Entropy 層級,做為原則。 這類原則通常會將最小 Entropy 層級設定為 128 位或更高版本。 將 NewGuid 的輸出傳遞至這類常式可能會違反其原則。

如果應用程式需要亂數據進行密碼編譯,請考慮在 RandomNumberGenerator 類別上使用靜態方法。 該類別提供適合密碼編譯使用的亂數產生器。

適用於