跳過到頁腳內容
.NET幫助

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

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

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

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

此設計選擇允許直接存取所包含的物件,而不需要封裝的開銷。 此外,在文章的最後,我們將探討如何使用 Iron Software Overview 中的 IronPDF 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

元組之好處

簡潔的語法

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> 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>
  • ImmutableDictionary<TKey, TValue>: 對於需要不可變性的場景,ImmutableDictionary<TKey, TValue> 來自 System.Collections.Immutable 命名空間提供了不可變的鍵值集合。
  • 自訂 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

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 類別?

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

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

Pair類與Tuple的區別在於,它通過公共字段直接暴露其對象引用,提高了可讀性和靈活性。另一方面,Tuple是不可變的,通過像Item1Item2這樣的屬性訪問其元素。

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

使用Pair類而不是元組的優點包括通過使用描述性屬性名稱來提高代碼可讀性,而不是Item1Item2,以及由於Pair是可變的,能夠修改值。

我可以使用 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核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

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

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

鋼鐵支援團隊

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