跳至頁尾內容
.NET幫助

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

一對是一種簡單的資料結構,用於保存兩個相關的值。 它提供了一種將兩個不同的資料捆綁在一起的便利方法。 當一個方法需要返回兩個值或處理鍵值關聯時,成對結構常被使用。

在C#中,開發人員通常使用元組 (Tuple<T1, T2>) 來配對值。 然而,元組是不可變的,它們的元素通過如 Item1 和 Item2 的屬性存取,這在廣泛使用時可能導致程式碼不太易讀。 這就是自定義 Pair 類別能派上用場的地方。

如果您需要一個結構來保存兩個相關的物件,且資料隱藏不是優先考量,您可以在程式碼中使用 Pair 類別。 Pair 類別不封裝其物件引用。 相反,它直接以公共類別欄位形式暴露給所有調用程式碼。

這種設計選擇允許直接存取所包含的物件,避免了封裝的額外負擔。 此外,在文章的最後,我們將探索如何使用 Iron Software OverviewIronPDF for PDF Generation 生成PDF文件。

元組

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> in C

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>
  • System.Collections.Immutable 名稱空間下的 ImmutableDictionary<TKey, TValue> 提供不可變鍵值集合。
  • 自定義鍵值對類別:在需要額外功能或特定行為的情況下,考慮建立符合您需求的自定義鍵值對類別。

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 以如下方式安裝:

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): Figure 2

IronPDF 試用授權

獲取您的 IronPDF 試用授權 並將授權放入 appsettings.json

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

結論

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

無論是處理座標、從方法返回多個值,還是儲存鍵值關聯,Pair 類別都是您編程技能集中寶貴的補充。

除此之外,IronPDF 程式庫功能 是開發人員用於即時生成應用程式所需 PDF 文件的重要技術能力。

常見問題

什麼是C#中的Pair類別?

C#中的Pair類別是一種簡單的資料結構,旨在保存兩個相關的值。它允許通過公共字段直接存取其屬性,當封裝不是優先考慮時,這是一種方便的元組替代方案。

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

Pair類別與Tuple不同之處在於,它通過公共字段直接暴露其物件引用,增強了可讀性和靈活性。而Tuple是不可變的,並且通過像Item1Item2這樣的屬性存取其元素。

使用Pair類別的優點是什麼?

使用Pair類別比元組的優點包括使用描述性屬性名稱而不是Item1Item2提高程式碼可讀性,以及能夠修改值,因為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),增強了開發者工具組,對於處理複雜的資料和文件工作流程非常有價值。

Jacob Mellor,首席技術官 @ Team Iron
首席技術官

Jacob Mellor是Iron Software的首席技術官,一位在C# PDF技術上開創先河的遠見工程師。作為Iron Software核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。

Jacob擁有曼徹斯特大學的土木工程一等榮譽學士學位(BEng),於1998-2001年之間獲得。在1999年於倫敦創辦他的第一家軟體公司並於2005年建立了他的第一批.NET元組件後,他專注於解決Microsoft生態系統中的複雜問題。

他的旗艦IronPDF和Iron Suite .NET程式庫在全球獲得了超過3000萬次NuGet安裝依據,他的基礎程式碼基繼續支援著世界各地開發者使用的工具。擁有25年的商業經驗和41年的程式設計專業知識,他仍專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話