跳過到頁腳內容
.NET幫助

C# Pair Class(對於開發者的運行原理)

資料對是一種簡單的資料結構,可保存兩個相關的值。 它提供了一種方便的方式,將兩種截然不同的資料捆綁在一起。 當一個方法需要回傳兩個值或處理鍵值關聯時,通常會使用 Pairs。

在 C# 中,開發人員通常會使用元組來配對值 (Tuple<T1, T2>)。 然而,元組是不可變的,其元素可透過 Item1 和 Item2 等屬性存取,因此大量使用時可能會導致程式碼的可讀性降低。 這就是自訂 Pair 類別派上用場的地方。

如果您需要一個結構來存放兩個相關的物件,而且資料隱藏並不是優先考量,您可以在程式碼中利用 Pair 類別。 Pair 類別沒有封裝其物件參照。 在翻譯過程中,我們不會將這些工具的功能和優點說明清楚,而是將它們以公開類別欄位的形式直接公開給所有的呼叫代碼。

此設計選擇允許直接存取所包含的物件,而不需要封裝的開銷。 此外,在文章的最後,我們將探討如何使用 Iron Software Overview 中的 IronPDF for PDF Generation 來產生 PDF 文件。

Tuples

C# 7.0 引入了元組語法改進,使元組更容易使用。 以下是如何宣告和初始化元組資料:

// Tuple declaration
var person = (name: "John", age: 30);

// Accessing tuple elements using named properties
Console.WriteLine($"Name: {person.name}, Age: {person.age}");

// Tuple deconstruction
var (name, age) = person;
Console.WriteLine($"Name: {name}, Age: {age}");
// Tuple declaration
var person = (name: "John", age: 30);

// Accessing tuple elements using named properties
Console.WriteLine($"Name: {person.name}, Age: {person.age}");

// Tuple deconstruction
var (name, age) = person;
Console.WriteLine($"Name: {name}, Age: {age}");
' Tuple declaration
Dim person = (name:= "John", age:= 30)

' Accessing tuple elements using named properties
Console.WriteLine($"Name: {person.name}, Age: {person.age}")

' Tuple deconstruction
'INSTANT VB TODO TASK: VB has no equivalent to C# deconstruction declarations:
var(name, age) = person
Console.WriteLine($"Name: {name}, Age: {age}")
$vbLabelText   $csharpLabel

元組之好處

簡潔的語法

Tuples 可讓您使用簡潔的語法表達複雜的資料結構,而不需要定義自訂的類別或結構。

輕量級

Tuples 是輕量級的資料結構,因此適用於需要暫時或中間儲存資料的情況。

隱含命名

使用元组语法,您可以隐式命名元组元素,增强代码的可读性并减少注释的需要。

從方法返回多個值

public (int Quotient, int Remainder) Divide(int dividend, int divisor)
{
    int quotient = dividend / divisor;
    int remainder = dividend % divisor;
    return (quotient, remainder);
}

var result = Divide(10, 3);
Console.WriteLine($"Quotient: {result.Quotient}, Remainder: {result.Remainder}");
public (int Quotient, int Remainder) Divide(int dividend, int divisor)
{
    int quotient = dividend / divisor;
    int remainder = dividend % divisor;
    return (quotient, remainder);
}

var result = Divide(10, 3);
Console.WriteLine($"Quotient: {result.Quotient}, Remainder: {result.Remainder}");
Public Function Divide(ByVal dividend As Integer, ByVal divisor As Integer) As (Quotient As Integer, Remainder As Integer)
	Dim quotient As Integer = dividend \ divisor
	Dim remainder As Integer = dividend Mod divisor
	Return (quotient, remainder)
End Function

Private result = Divide(10, 3)
Console.WriteLine($"Quotient: {result.Quotient}, Remainder: {result.Remainder}")
$vbLabelText   $csharpLabel

簡化方法簽章

public (string Name, string Surname) GetNameAndSurname()
{
    // Retrieve name and surname from a data source
    return ("John", "Doe");
}

var (name, surname) = GetNameAndSurname();
Console.WriteLine($"Name: {name}, Surname: {surname}");
public (string Name, string Surname) GetNameAndSurname()
{
    // Retrieve name and surname from a data source
    return ("John", "Doe");
}

var (name, surname) = GetNameAndSurname();
Console.WriteLine($"Name: {name}, Surname: {surname}");
Public Function GetNameAndSurname() As (Name As String, Surname As String)
	' Retrieve name and surname from a data source
	Return ("John", "Doe")
End Function

'INSTANT VB TODO TASK: VB has no equivalent to C# deconstruction declarations:
var(name, surname) = GetNameAndSurname()
Console.WriteLine($"Name: {name}, Surname: {surname}")
$vbLabelText   $csharpLabel

群組相關資料

var point = (x: 10, y: 20);
var color = (r: 255, g: 0, b: 0);
var person = (name: "Alice", age: 25);
var point = (x: 10, y: 20);
var color = (r: 255, g: 0, b: 0);
var person = (name: "Alice", age: 25);
Dim point = (x:= 10, y:= 20)
Dim color = (r:= 255, g:= 0, b:= 0)
Dim person = (name:= "Alice", age:= 25)
$vbLabelText   $csharpLabel

限制與注意事項

雖然 C# 7.0 元組能提供顯著的優點,但也有一些限制和注意事項需要牢記:

  • 與自訂類別或結構體相較,元組表達能力有限。
  • Tuple 元素在未提供明確名稱時,會使用 Item1、Item2 等存取,這會降低程式碼的可讀性。

配對自訂類別

public class Pair<T1, T2>
{
    public T1 First { get; set; }
    public T2 Second { get; set; }

    // Constructor to initialize the pair
    public Pair(T1 first, T2 second)
    {
        First = first;
        Second = second;
    }
}
public class Pair<T1, T2>
{
    public T1 First { get; set; }
    public T2 Second { get; set; }

    // Constructor to initialize the pair
    public Pair(T1 first, T2 second)
    {
        First = first;
        Second = second;
    }
}
Public Class Pair(Of T1, T2)
	Public Property First() As T1
	Public Property Second() As T2

	' Constructor to initialize the pair
	Public Sub New(ByVal first As T1, ByVal second As T2)
		Me.First = first
		Me.Second = second
	End Sub
End Class
$vbLabelText   $csharpLabel

在這個類別中,類型是在使用時定義的,而兩個屬性是以公開屬性的方式公開。

使用 Pair 類別

現在,讓我們來探討一些常見的使用案例,在這些案例中,Pair class 可以發揮作用:

1.儲存座標

// Creating a new instance of the Pair class to store coordinates
Pair<int, int> coordinates = new Pair<int, int>(10, 20);
Console.WriteLine($"X: {coordinates.First}, Y: {coordinates.Second}");
// Creating a new instance of the Pair class to store coordinates
Pair<int, int> coordinates = new Pair<int, int>(10, 20);
Console.WriteLine($"X: {coordinates.First}, Y: {coordinates.Second}");
' Creating a new instance of the Pair class to store coordinates
Dim coordinates As New Pair(Of Integer, Integer)(10, 20)
Console.WriteLine($"X: {coordinates.First}, Y: {coordinates.Second}")
$vbLabelText   $csharpLabel

2.從一個方法返回多個值。

// Method returning a Pair, representing both quotient and remainder
public Pair<int, int> Divide(int dividend, int divisor)
{
    int quotient = dividend / divisor;
    int remainder = dividend % divisor;
    return new Pair<int, int>(quotient, remainder);
}

// Usage
Pair<int, int> result = Divide(10, 3);
Console.WriteLine($"Quotient: {result.First}, Remainder: {result.Second}");
// Method returning a Pair, representing both quotient and remainder
public Pair<int, int> Divide(int dividend, int divisor)
{
    int quotient = dividend / divisor;
    int remainder = dividend % divisor;
    return new Pair<int, int>(quotient, remainder);
}

// Usage
Pair<int, int> result = Divide(10, 3);
Console.WriteLine($"Quotient: {result.First}, Remainder: {result.Second}");
' Method returning a Pair, representing both quotient and remainder
Public Function Divide(ByVal dividend As Integer, ByVal divisor As Integer) As Pair(Of Integer, Integer)
	Dim quotient As Integer = dividend \ divisor
	Dim remainder As Integer = dividend Mod divisor
	Return New Pair(Of Integer, Integer)(quotient, remainder)
End Function

' Usage
Private result As Pair(Of Integer, Integer) = Divide(10, 3)
Console.WriteLine($"Quotient: {result.First}, Remainder: {result.Second}")
$vbLabelText   $csharpLabel

3.儲存鍵-值對

// Storing a key-value pair
Pair<string, int> keyValue = new Pair<string, int>("Age", 30);
Console.WriteLine($"Key: {keyValue.First}, Value: {keyValue.Second}");
// Storing a key-value pair
Pair<string, int> keyValue = new Pair<string, int>("Age", 30);
Console.WriteLine($"Key: {keyValue.First}, Value: {keyValue.Second}");
' Storing a key-value pair
Dim keyValue As New Pair(Of String, Integer)("Age", 30)
Console.WriteLine($"Key: {keyValue.First}, Value: {keyValue.Second}")
$vbLabelText   $csharpLabel

關鍵值對

鍵值對提供簡單有效的資料關聯方式。 在 C# 中,處理鍵-值對的主要工具是 Dictionary<TKey, TValue> 類別,這是一種多用途且功能強大的集合類型。

瞭解鍵-值對

鍵值對是一種資料結構,可將唯一的鍵與值聯繫起來。 此聯繫可根據資料的唯一識別碼進行有效的檢索和操作。 在 C# 中,鍵值對通常用於快取、組態管理和資料儲存等工作。

Dictionary<TKey, TValue> 在 C#&num 中;。

C# 中的 Dictionary<TKey, TValue> 類是儲存鍵值對的一般集合。 它提供基於鍵的快速查詢,並廣泛用於管理關聯資料。

建立和填充字典

Dictionary<string, int> ages = new Dictionary<string, int>
{
    { "Alice", 30 },
    { "Bob", 35 },
    { "Charlie", 25 }
};
Dictionary<string, int> ages = new Dictionary<string, int>
{
    { "Alice", 30 },
    { "Bob", 35 },
    { "Charlie", 25 }
};
Dim ages As New Dictionary(Of String, Integer) From {
	{"Alice", 30},
	{"Bob", 35},
	{"Charlie", 25}
}
$vbLabelText   $csharpLabel

依鍵取值

// Directly access a value by its key
Console.WriteLine($"Alice's age: {ages["Alice"]}");
// Directly access a value by its key
Console.WriteLine($"Alice's age: {ages["Alice"]}");
' Directly access a value by its key
Console.WriteLine($"Alice's age: {ages("Alice")}")
$vbLabelText   $csharpLabel

迭代鍵-值對

// Iterate over all key-value pairs in the dictionary
foreach (var pair in ages)
{
    Console.WriteLine($"Name: {pair.Key}, Age: {pair.Value}");
}
// Iterate over all key-value pairs in the dictionary
foreach (var pair in ages)
{
    Console.WriteLine($"Name: {pair.Key}, Age: {pair.Value}");
}
' Iterate over all key-value pairs in the dictionary
For Each pair In ages
	Console.WriteLine($"Name: {pair.Key}, Age: {pair.Value}")
Next pair
$vbLabelText   $csharpLabel

進階方案

處理遺失的鍵

if (ages.TryGetValue("David", out int age))
{
    Console.WriteLine($"David's age: {age}");
}
else
{
    Console.WriteLine("David's age is not available.");
}
if (ages.TryGetValue("David", out int age))
{
    Console.WriteLine($"David's age: {age}");
}
else
{
    Console.WriteLine("David's age is not available.");
}
Dim age As Integer
If ages.TryGetValue("David", age) Then
	Console.WriteLine($"David's age: {age}")
Else
	Console.WriteLine("David's age is not available.")
End If
$vbLabelText   $csharpLabel

移除項目

// Remove an entry given its key
ages.Remove("Charlie");
// Remove an entry given its key
ages.Remove("Charlie");
' Remove an entry given its key
ages.Remove("Charlie")
$vbLabelText   $csharpLabel

字典初始化

// Initialize a dictionary with color codes
var colors = new Dictionary<string, string>
{
    { "red", "#FF0000" },
    { "green", "#00FF00" },
    { "blue", "#0000FF" }
};
// Initialize a dictionary with color codes
var colors = new Dictionary<string, string>
{
    { "red", "#FF0000" },
    { "green", "#00FF00" },
    { "blue", "#0000FF" }
};
' Initialize a dictionary with color codes
Dim colors = New Dictionary(Of String, String) From {
	{"red", "#FF0000"},
	{"green", "#00FF00"},
	{"blue", "#0000FF"}
}
$vbLabelText   $csharpLabel

字典之外:替代方案和考慮因素

雖然 Dictionary<TKey, TValue> 是一個功能強大的工具,但替代方法和考慮因素取決於您應用程式的特定需求:

  • ConcurrentDictionary<TKey, TValue>: 如果您的應用程式需要從多個線程以線程安全的方式存取字典,請考慮使用 ConcurrentDictionary<TKey, TValue>
  • ImmutableDictionary<TKey,TValue>:針對需要不可變的場景,System.Collections.Immutable命名空間中的 ImmutableDictionary<TKey, TValue> 提供了不可變的鍵值集合。
  • 自訂 Key-Value Pair 類別:在您需要額外功能或特定行為的情況下,請考慮建立符合您需求的客製化鍵值對類別。

IronPDF 資料庫。

Iron Software Products 的 IronPDF 是生成 PDF 文件的出色库。 其易用性和效率首屈一指。

IronPDF 擅長於 HTML 至 PDF 的轉換,可確保精確保留原始版面與樣式。 它非常適合從網頁內容(如報告、發票和文件)建立 PDF。 IronPDF 支援 HTML 檔案、URL 和原始 HTML 字串,可輕鬆製作高品質的 PDF 文件。

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

IronPDF 可從 NuGet 套件管理程式安裝:

Install-Package IronPdf

或者像這樣從 Visual Studio

!a href="/static-assets/pdf/blog/csharp-pair-class/csharp-pair-class-1.webp">C# Pair Class (How It Works For Developers):圖 1 - 使用 NuGet 套件管理員安裝 IronPDF

若要產生一份包含元組範例的文件,我們可以使用下列程式碼:

using IronPdf;

namespace IronPatterns
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("-----------Iron Software-------------");
            var renderer = new ChromePdfRenderer(); // var pattern
            var content = "<h1>Iron Software is Awesome</h1> Made with IronPDF!";
            content += "<h2>Demo C# Pair with Tuples</h2>";

            var result = Divide(10, 3);
            Console.WriteLine($"Quotient: {result.Item1}, Remainder: {result.Item2}");
            content += $"<p>When we divide 10 by 3:</p>";
            content += $"<p>Quotient: {result.Item1}, Remainder: {result.Item2}</p>";

            var pdf = renderer.RenderHtmlAsPdf(content);
            pdf.SaveAs("output.pdf"); // Saves PDF
        }

        // Method to demonstrate division using tuples
        public static (int Quotient, int Remainder) Divide(int dividend, int divisor)
        {
            int quotient = dividend / divisor;
            int remainder = dividend % divisor;
            return (quotient, remainder);
        }
    }
}
using IronPdf;

namespace IronPatterns
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("-----------Iron Software-------------");
            var renderer = new ChromePdfRenderer(); // var pattern
            var content = "<h1>Iron Software is Awesome</h1> Made with IronPDF!";
            content += "<h2>Demo C# Pair with Tuples</h2>";

            var result = Divide(10, 3);
            Console.WriteLine($"Quotient: {result.Item1}, Remainder: {result.Item2}");
            content += $"<p>When we divide 10 by 3:</p>";
            content += $"<p>Quotient: {result.Item1}, Remainder: {result.Item2}</p>";

            var pdf = renderer.RenderHtmlAsPdf(content);
            pdf.SaveAs("output.pdf"); // Saves PDF
        }

        // Method to demonstrate division using tuples
        public static (int Quotient, int Remainder) Divide(int dividend, int divisor)
        {
            int quotient = dividend / divisor;
            int remainder = dividend % divisor;
            return (quotient, remainder);
        }
    }
}
Imports IronPdf

Namespace IronPatterns
	Friend Class Program
		Shared Sub Main()
			Console.WriteLine("-----------Iron Software-------------")
			Dim renderer = New ChromePdfRenderer() ' var pattern
			Dim content = "<h1>Iron Software is Awesome</h1> Made with IronPDF!"
			content &= "<h2>Demo C# Pair with Tuples</h2>"

			Dim result = Divide(10, 3)
			Console.WriteLine($"Quotient: {result.Item1}, Remainder: {result.Item2}")
			content &= $"<p>When we divide 10 by 3:</p>"
			content &= $"<p>Quotient: {result.Item1}, Remainder: {result.Item2}</p>"

			Dim pdf = renderer.RenderHtmlAsPdf(content)
			pdf.SaveAs("output.pdf") ' Saves PDF
		End Sub

		' Method to demonstrate division using tuples
		Public Shared Function Divide(ByVal dividend As Integer, ByVal divisor As Integer) As (Quotient As Integer, Remainder As Integer)
			Dim quotient As Integer = dividend \ divisor
			Dim remainder As Integer = dividend Mod divisor
			Return (quotient, remainder)
		End Function
	End Class
End Namespace
$vbLabelText   $csharpLabel

輸出

C# Pair Class (How It Works For Developers):圖 2

IronPDF 的試用授權

取得IronPDF試用授權,並將授權放置在appsettings.json中。

{
    "IronPDF.LicenseKey": "<Your Key>"
}

結論

在這篇文章中,我們探討了成對的概念,以及在 C# 中擁有 Pair 類的重要性。 我們提供了 Pair 自訂類別的簡單實作,以及各種使用案例,展示其在日常程式設計工作中的多樣性與實用性。

無論您是要處理座標、從一個方法回傳多個值,或是儲存鍵值關聯,Pair 類別都可以成為您程式設計技能的重要補充。

除此之外,IronPDF 函式庫功能是開發人員必須具備的絕佳組合技能,可在應用程式中依需求即時產生 PDF 文件。

常見問題解答

什麼是 C# 中的 Pair class?

C# 中的 Pair 類別是一種簡單的資料結構,設計用來存放兩個相關的值。它允許以公開欄位的方式直接存取其屬性,當封裝不是優先考量時,它是一個方便的元組替代品。

Pair 類別與 C# 中的 Tuple 有何不同?

Pair 類別與 Tuple 的不同之處在於它直接透過公共欄位揭露其物件參照,增強了可讀性與彈性。另一方面,Tuple 是不可變的,並且可以透過 Item1Item2 之類的屬性存取其元素。

與元組相比,使用 Pair 類有哪些優點?

與 tuples 相比,使用 Pair 類的優點包括使用描述性的屬性名稱取代 Item1Item2 來改善程式碼的可讀性,以及由於 Pairs 是可變的,因此可以修改值。

我可以使用 Pair 類別來儲存key-value 對嗎?

是的,與 tuples 相比,Pair 類別對於以更易讀的方式儲存 key-value 對特別有用,因為它可以透過公共欄位直接存取值。

在 C# 中使用 Pair 類的常見情況有哪些?

使用 Pair 類的常見情況包括:儲存座標、從一個方法返回多個值,以及以可讀取的格式管理鍵值對關聯。

開發人員為何會選擇使用 IronPDF 函式庫?

開發人員可能會選擇使用 IronPDF 函式庫來從 HTML 內容產生 PDF。它可以確保保留原始版面與風格,簡化報告和發票等專業文件的製作。

如何用 C# 從 HTML 檔案產生 PDF?

您可以使用 IronPDF 函式庫以 C# 從 HTML 檔案產生 PDF。它提供了一些方法,例如 RenderHtmlAsPdf 來將 HTML 字串和檔案轉換成高品質的 PDF 文件。

使用函式庫產生 PDF 有什麼好處?

使用 IronPDF 之類的函式庫來產生 PDF,可以簡化製作高品質 PDF 文件的流程,確保各種內容來源的排版和樣式都能精確保存。

Pair class 和 IronPDF 函式庫在開發人員的工具包中扮演什麼角色?

Pair 類和 IronPDF 函式庫可透過 Pairs 提供高效率的資料結構管理,並透過 IronPDF 提供可靠的文件產生功能,進而強化開發人員的工具包,使其在處理複雜資料和文件工作流程時非常有價值。

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 技術的創新,同時指導新一代技術領袖。