跳過到頁腳內容
.NET幫助

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

配對是一種簡單的數據結構,用於保存兩個相關的值。 它提供了一種方便的方法將兩個不同的數據捆綁在一起。 當一個方法需要返回兩個值或處理鍵值關係時,配對通常會被應用。

在 C# 中,開發人員通常會使用元組(Tuple<T1, T2>)來配對值。 然而,元組是不可變的,其元素通過像 Item1 和 Item2 這樣的屬性來訪問,當廣泛使用時會導致代碼可讀性下降。 這就是自定義 Pair 類派上用場的地方。

如果您需要一個結構來保存兩個相關的對象而數據隱藏不是首要考慮,可以在您的代碼中使用 Pair 類。 Pair 類不對其對象引用進行封裝。 相反,它將這些對象作為公共類字段直接暴露給所有調用代碼。

這種設計選擇允許直接訪問所包含的對象,而無需承擔封裝的額外開銷。 Also, at the end of the article, we will explore how IronPDF for PDF Generation from Iron Software Overview can be used to generate a PDF document.

元組

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

元組的優勢

簡潔的語法

元組讓您可以用簡潔的語法表達複雜的數據結構,而無需定義自定義類或結構。

輕量級

元組是輕量級數據結構,適合那些需要臨時或中間數據存儲的場景。

隱式命名

通過元組語法,您可以隱式地命名元組元素,提高代碼可讀性並減少注釋需求。

方法返回多個值

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 的元組帶來了顯著的優勢,但仍有一些限制和注意事項需要記住:

  • 與自定義類或結構相比,元組在表達性方面有限。
  • 當未提供顯式名稱時,元組元素使用 Item1、Item2 等訪問,這可能會降低代碼可讀性。

自定義 Pair 類

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 類可以帶來好處的常見用例:

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# 中

Dictionary<TKey, TValue> 類是 C# 中的一個通用集合,用於存儲鍵值對。 它提供基於鍵的快速查找,廣泛用於管理關聯數據。

創建和填充字典

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> 提供不變的鍵值集合。
  • 自定義鍵值對類:在需要額外功能或特定行為的情況下,考慮建立自定義鍵值對類。

IronPDF 庫

IronPDF by Iron Software Products 是一個生成 PDF 文檔的優秀庫。 它的易用性和效率無與倫比。

IronPDF 在HTML 到 PDF轉換方麵表現出色,確保準確保持原始佈局和樣式。 它非常適合從網路內容生成 PDF,如報告、發票和文檔。 支持 HTML 文件、URL 和原始 HTML 字串的 IronPDF 可以輕鬆生成高質量的 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 中這樣安裝:

C# 配對類(對開發者的運作方式):圖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# 配對類(對開發者的運作方式):圖2

IronPDF 的試用許可

獲取您的 IronPDF 試用許可 並將許可放在 appsettings.json

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

結論

在本文中,我們探討了配對的概念以及在 C# 中擁有 Pair 類的重要性。 我們提供了一個簡單的 Pair 自定義類實現,以及展示其在日常編程任務中多功能性和實用性的多種用例。

無論您是處理坐標、從方法返回多個值,還是存儲鍵值關聯,Pair 類對於您的編程技能來說都是一個有價值的補充。

除此之外,IronPDF 庫功能 對於開發者來說是一項很好的技能組合,可以按照應用需要即時生成 PDF 文檔。

常見問題解答

什麼是 C# 中的 Pair 類別?

C# 中的 Pair 類別是一種設計用來保存兩個相關值的簡單數據結構。當封裝不是優先事項時,它允許通過公有字段直接訪問其屬性,是元組方便的替代方案。

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

Pair 類別的不同之處在於它通過公有字段直接公開其對象引用,增強了可讀性和靈活性。而元組是不可變的並通過如 Item1 和 Item2 的屬性訪問其元素。

使用 Pair 類別比使用元組有什麼優勢?

使用 Pair 類別比使用元組的優勢包括通過描述性屬性名稱(而不是 Item1 和 Item2)提高代碼可讀性,並且因為 Pairs 是可變的,可以修改值。

我可以使用 Pair 類別來存儲鍵值對嗎?

可以,Pair 類別尤其適合於以更可讀的方式存儲鍵值對,因為它通過公有字段直接訪問值,相比於元組更為直觀。

使用 C# 中的 Pair 類別的常見場景有哪些?

使用 Pair 類別的常見場景包括存儲坐標、從方法返回多個值,以及以可讀格式管理鍵值對關聯。

為什麼開發人員會選擇使用 IronPDF 庫?

開發者可能會選擇使用 IronPDF 庫來從 HTML 內容生成 PDF。它確保原始布局和樣式得到保留,簡化了像報告和發票這樣專業文檔的創建。

如何在 C# 中從 HTML 文件生成 PDF?

您可以使用 IronPDF 庫在 C# 中從 HTML 文件生成 PDF。它提供了如 RenderHtmlAsPdf 這樣的方法,將 HTML 字符串和文件轉換為高品質的 PDF 文檔。

使用庫生成 PDF 有何優勢?

使用像 IronPDF 這樣的庫進行 PDF 生成提供了簡化的過程,用於創建高質量的 PDF 文檔,確保來自各種內容源的準確佈局和樣式保留。

Pair 類別和 IronPDF 庫在開發人員的工具箱中扮演什麼角色?

Pair 類別和 IronPDF 庫通過提供 Pairs 的有效數據結構管理和 IronPDF 的可靠文檔生成能力,提升了開發人員的工具箱,使其對於處理複雜數據和文檔工作流程非常有價值。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。