跳過到頁腳內容
.NET幫助

C#新GUID(對開發者如何理解的工作)

Guid 類別中的 NewGuid() 方法 常用於建立全球唯一的識別碼 (GUID)。 GUID 是 128 位元的整數,可在所有電腦和網路中使用,以唯一方式識別資訊,而不會有重複的風險。 本文將深入介紹如何在 C# 中使用 GUID(全球唯一 IDentifiers),著重於實際用途、範例和程式碼片段。 我們也將探討 IronPDF 函式庫

什麼是 GUID?

GUID(全球唯一識別碼)是軟體開發中使用的唯一識別碼。 在 .NET Framework 中,GUID 在 System 命名空間中表示為一個 Guid 結構。 GUID 通常用於資料庫的主索引鍵,也用於其他系統中的其他用途,在這些系統中,各系統之間都需要唯一的識別碼。

在 C# 中生成 GUID;

要在 C# 中產生新的 GUID,需要使用 Guid.NewGuid() 函式。 此方法會建立 GUID 物件的新實體,並確保產生的每個 GUID 都是唯一的。 內部使用隨機數字產生器產生 GUID,以確保沒有兩個 GUID 具有相同的值。

以下是一個產生新 GUID 的簡單程式碼範例:

using System;

class Program
{
    static void Main()
    {
        // Generate a new GUID
        Guid newGuid = Guid.NewGuid();

        // Output the newly generated GUID to the console
        Console.WriteLine(newGuid);
    }
}
using System;

class Program
{
    static void Main()
    {
        // Generate a new GUID
        Guid newGuid = Guid.NewGuid();

        // Output the newly generated GUID to the console
        Console.WriteLine(newGuid);
    }
}
Imports System

Friend Class Program
	Shared Sub Main()
		' Generate a new GUID
		Dim newGuid As Guid = Guid.NewGuid()

		' Output the newly generated GUID to the console
		Console.WriteLine(newGuid)
	End Sub
End Class
$vbLabelText   $csharpLabel

在此代碼中,Guid.NewGuid() 方法在內部使用隨機數字產生器建立新的 GUID,而 Console.WriteLine 則將新產生的 GUID 輸出到控制台。

GUID 結構與格式

GUID 由 32 個十六進位數字組成,通常以 8-4-4-4-12 的格式顯示(例如,e02fd0e4-00fd-090A-ca30-0d00a0038ba0)。 當使用 ToString() 方法轉換為字串時,GUID 會以這種格式表示。 此表示法可讓您輕鬆地將 GUID 儲存在以文字為基礎的格式中,例如 JSON、XML 或資料庫。

下面的程式碼範例顯示如何將 GUID 轉換成字串:

using System;

class Example
{
    static void Main()
    {
        // Generate a new GUID
        Guid newGuid = Guid.NewGuid();

        // Convert the GUID to a string
        string guidString = newGuid.ToString();

        // Output the GUID string
        Console.WriteLine(guidString);
    }
}
using System;

class Example
{
    static void Main()
    {
        // Generate a new GUID
        Guid newGuid = Guid.NewGuid();

        // Convert the GUID to a string
        string guidString = newGuid.ToString();

        // Output the GUID string
        Console.WriteLine(guidString);
    }
}
Imports System

Friend Class Example
	Shared Sub Main()
		' Generate a new GUID
		Dim newGuid As Guid = Guid.NewGuid()

		' Convert the GUID to a string
		Dim guidString As String = newGuid.ToString()

		' Output the GUID string
		Console.WriteLine(guidString)
	End Sub
End Class
$vbLabelText   $csharpLabel

此代碼會將 GUID 轉換成字串並輸出。

解析 GUID 字串

有時候,您可能需要將字串解析回 GUID 物件。 這是使用 Guid.Parse() 方法完成的。 如果字串格式正確,則會解析為 GUID 實例。 如果格式不正確,將會產生異常。

以下是一個程式碼範例:

using System;

class ParseExample
{
    static void Main()
    {
        // Define a GUID string
        string guidString = "e02fd0e4-00fd-090A-ca30-0d00a0038ba0";

        // Convert the string back into a GUID object
        Guid parsedGuid = Guid.Parse(guidString);

        // Output the parsed GUID
        Console.WriteLine(parsedGuid);
    }
}
using System;

class ParseExample
{
    static void Main()
    {
        // Define a GUID string
        string guidString = "e02fd0e4-00fd-090A-ca30-0d00a0038ba0";

        // Convert the string back into a GUID object
        Guid parsedGuid = Guid.Parse(guidString);

        // Output the parsed GUID
        Console.WriteLine(parsedGuid);
    }
}
Imports System

Friend Class ParseExample
	Shared Sub Main()
		' Define a GUID string
		Dim guidString As String = "e02fd0e4-00fd-090A-ca30-0d00a0038ba0"

		' Convert the string back into a GUID object
		Dim parsedGuid As Guid = Guid.Parse(guidString)

		' Output the parsed GUID
		Console.WriteLine(parsedGuid)
	End Sub
End Class
$vbLabelText   $csharpLabel

在此程式碼中,Guid.Parse() 方法會將字串轉換回 GUID 物件。

比較兩個 GUID。

可以比較 GUID 是否相等。 Guid 結構體實作了相等運算符號 (===),因此您可以直接比較兩個 GUID 物件。

以下是一個範例:

using System;

class CompareExample
{
    static void Main()
    {
        // Generate two new GUIDs
        Guid guid1 = Guid.NewGuid();
        Guid guid2 = Guid.NewGuid();

        // Compare the two GUIDs
        if (guid1 == guid2)
        {
            Console.WriteLine("The two GUIDs are the same.");
        }
        else
        {
            Console.WriteLine("The two GUIDs are different.");
        }
    }
}
using System;

class CompareExample
{
    static void Main()
    {
        // Generate two new GUIDs
        Guid guid1 = Guid.NewGuid();
        Guid guid2 = Guid.NewGuid();

        // Compare the two GUIDs
        if (guid1 == guid2)
        {
            Console.WriteLine("The two GUIDs are the same.");
        }
        else
        {
            Console.WriteLine("The two GUIDs are different.");
        }
    }
}
Imports System

Friend Class CompareExample
	Shared Sub Main()
		' Generate two new GUIDs
		Dim guid1 As Guid = Guid.NewGuid()
		Dim guid2 As Guid = Guid.NewGuid()

		' Compare the two GUIDs
		If guid1 = guid2 Then
			Console.WriteLine("The two GUIDs are the same.")
		Else
			Console.WriteLine("The two GUIDs are different.")
		End If
	End Sub
End Class
$vbLabelText   $csharpLabel

在此程式碼中,兩個 GUID 會進行比較。 由於 Guid.NewGuid() 產生的每個 GUID 都是唯一的,因此結果通常會是 "The two GUIDs are different"。

使用 GUID 時的常見錯誤

1.Assuming GUIDs Are Sequential: GUIDs 是隨機的,而 NewGuid() 方法不會產生序列值。 因此,您不應假設 GUID 會維持任何一種順序。

2.以字串比較取代 GUID 比較:以字串比較 GUID 可能效率不高。 務必直接比較 GUID 物件,而非將其轉換為字串並比較字串值。

3.在大型資料庫中使用 GUID 而不建立索引:GUID 可能很大,如果不適當建立索引,可能會影響大型資料庫的效能。 使用 GUID 列作為主索引鍵時,請確保它們已被索引。

.NET Core 和 Framework 中的 GUID。

.NET Framework 和 .NET Core 均支援 GUID。 Guid 類的用法在不同版本的 .NET 平台上保持一致。 因此,使用任何版本 .NET 的開發人員都可以使用 Guid.NewGuid() 方法輕鬆產生 GUID。

GUID vs UUID

GUID 類似於 UUID(Universally Unique Identifiers,通用唯一識別碼),這兩個詞通常可以交替使用。 雖然在規格上有一些微小的差異,但它們都是為了產生唯一識別碼的相同目的。

使用 IronPdf 與 GUID

C# New GUID (How It Works For Developers):圖 1 - IronPdf

IronPDF 是一個 PDF 函式庫,用於在 .NET 應用程式中 從 HTML 產生 PDF 以及其他 PDF 作業。 當您需要為 PDF 文件產生唯一的檔案名稱時,您可以將 IronPDF 與 GUID 相結合。 這可確保產生的每個 PDF 都有唯一的名稱,防止任何檔案覆寫或命名衝突。 以下是一個使用 IronPdf 與新 GUID 的簡單範例:

using System;
using IronPdf;

class Program
{
    static void Main()
    {
        // Generate a new GUID object for the PDF filename
        Guid pdfId = Guid.NewGuid();
        string filename = $"{pdfId}.pdf";

        // Create a PDF document using IronPDF
        var renderer = new ChromePdfRenderer();
        var pdfDocument = renderer.RenderHtmlAsPdf("<h1>Hello, World!</h1>");

        // Save the PDF with the unique filename
        pdfDocument.SaveAs(filename);
        Console.WriteLine($"PDF saved as: {filename}");
    }
}
using System;
using IronPdf;

class Program
{
    static void Main()
    {
        // Generate a new GUID object for the PDF filename
        Guid pdfId = Guid.NewGuid();
        string filename = $"{pdfId}.pdf";

        // Create a PDF document using IronPDF
        var renderer = new ChromePdfRenderer();
        var pdfDocument = renderer.RenderHtmlAsPdf("<h1>Hello, World!</h1>");

        // Save the PDF with the unique filename
        pdfDocument.SaveAs(filename);
        Console.WriteLine($"PDF saved as: {filename}");
    }
}
Imports System
Imports IronPdf

Friend Class Program
	Shared Sub Main()
		' Generate a new GUID object for the PDF filename
		Dim pdfId As Guid = Guid.NewGuid()
		Dim filename As String = $"{pdfId}.pdf"

		' Create a PDF document using IronPDF
		Dim renderer = New ChromePdfRenderer()
		Dim pdfDocument = renderer.RenderHtmlAsPdf("<h1>Hello, World!</h1>")

		' Save the PDF with the unique filename
		pdfDocument.SaveAs(filename)
		Console.WriteLine($"PDF saved as: {filename}")
	End Sub
End Class
$vbLabelText   $csharpLabel

在 Visual Studio 中執行上述程式碼並觀察輸出。

C# New GUID (How It Works For Developers):圖 2 - Visual Studio 控制台輸出

我們使用 Guid.NewGuid() 為每個 PDF 檔案建立唯一的隨機 GUID。此 GUID 會轉換為字串,並用作檔案名稱。

結論

C# New GUID (How It Works For Developers):圖 3 - 授權

在這篇文章中,我們介紹了 C# 中 GUID 的基本知識。 您已經看到如何產生新的 GUID、比較它們、從字串解析它們,以及在資料庫等實際情境中使用它們。 Guid.NewGuid() 方法可輕鬆產生 GUID 的新實例,確保每個識別碼在不同系統中都是唯一的。 在 .NET 中工作的開發人員可以依賴 GUID 在其應用程式中提供隨機性和唯一性。

IronPdf 深知在投資前進行測試的重要性,因此我們提供 免費試用。 您可以免費評估軟體的效能。如果您覺得有好處,授權費從 $799 開始。

常見問題解答

如何在 C# 中產生新的 GUID?

在 C# 中,您可以使用 Guid.NewGuid() 方法產生新的 GUID。這個函式會建立 GUID 物件的新實體,確保每個產生的 GUID 都是唯一的。

C# 中的 GUID 有哪些實際用途?

C# 中的 GUID 可用於為資料庫項目建立唯一的識別碼、為文件產生唯一的檔案名稱,以及確保分散式系統中的唯一性。

如何使用 GUID 管理 PDF 檔案名?

GUID 可與 PDF 生成程式庫整合,為 PDF 建立唯一的檔案名稱。這可防止命名衝突,並確保每個文件都有獨特的識別碼。

GUID 與 UUID 有何差異?

GUID 和 UUID 在本質上是相同的,都是為了產生唯一的識別碼。在軟體開發中,兩者經常交替使用。

您可以在 C# 中將 GUID 轉換為字串嗎?

是的,您可以使用 GUID 物件上的 ToString() 方法,在 C# 中將 GUID 轉換為字串。

如何在 C# 中從字串解析 GUID?

若要在 C# 中從字串解析 GUID,請使用 Guid.Parse() 方法。確保字串為正確的 GUID 格式以避免異常。

GUID 如何改善資料庫管理?

在資料庫中,GUID 可作為主鍵使用,以確保每筆記錄都是唯一可識別的,尤其是當資料在多個系統中同步時。

在 C# 中使用 GUID 時有哪些常見錯誤?

常見的錯誤包括假設 GUID 為順序、以字串而非直接比較 GUID,以及在大型資料庫中未使用適當的索引。

如何在 C# 中比較兩個 GUID?

您可以使用相等運算符號 (==) 在 C# 中比較兩個 GUID。這可讓您檢查兩個 GUID 是否相同或不同。

Jacob Mellor, Team Iron 首席技术官
首席技术官

Jacob Mellor 是 Iron Software 的首席技術官,作為 C# PDF 技術的先鋒工程師。作為 Iron Software 核心代碼的原作者,他自開始以來塑造了公司產品架構,與 CEO Cameron Rimington 一起將其轉變為一家擁有超過 50 名員工的公司,為 NASA、特斯拉 和 全世界政府機構服務。

Jacob 持有曼徹斯特大學土木工程一級榮譽学士工程學位(BEng) (1998-2001)。他於 1999 年在倫敦開設了他的第一家軟件公司,並於 2005 年製作了他的首個 .NET 組件,專注於解決 Microsoft 生態系統內的複雜問題。

他的旗艦產品 IronPDF & Iron Suite .NET 庫在全球 NuGet 被安裝超過 3000 萬次,其基礎代碼繼續為世界各地的開發工具提供動力。擁有 25 年的商業經驗和 41 年的編碼專業知識,Jacob 仍專注於推動企業級 C#、Java 及 Python PDF 技術的創新,同時指導新一代技術領袖。