C# Pair 類別(開發者如何理解其工作原理)
資料對是一種簡單的資料結構,可保存兩個相關的值。 它提供了一種方便的方式,將兩種截然不同的資料捆綁在一起。 當一個方法需要回傳兩個值或處理鍵值關聯時,通常會使用 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}");元組之好處
簡潔的語法
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 (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}");群組相關資料
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);限制與注意事項
雖然 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;
}
}在這個類別中,類型是在使用時定義的,而兩個屬性是以公開屬性的方式公開。
使用 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}");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}");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}");關鍵值對
鍵值對提供簡單有效的資料關聯方式。 在 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 }
};依鍵取值
// 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"]}");迭代鍵-值對
// 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}");
}進階方案
處理遺失的鍵
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.");
}移除項目
// Remove an entry given its key
ages.Remove("Charlie");// Remove an entry given its key
ages.Remove("Charlie");字典初始化
// 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" }
};字典之外:替代方案和考慮因素
雖然 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");
}
}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);
}
}
}輸出

IronPDF 的試用授權
取得IronPDF試用授權,並將授權放置在appsettings.json中。
{
"IronPDF.LicenseKey": "<Your Key>"
}結論
在這篇文章中,我們探討了成對的概念,以及在 C# 中擁有 Pair 類的重要性。 我們提供了 Pair 自訂類別的簡單實作,以及各種使用案例,展示其在日常程式設計工作中的多樣性與實用性。
無論您是要處理座標、從一個方法回傳多個值,或是儲存鍵值關聯,Pair 類別都可以成為您程式設計技能的重要補充。
除此之外,IronPDF 函式庫功能是開發人員必須具備的絕佳組合技能,可在應用程式中依需求即時產生 PDF 文件。
常見問題解答
C# 中的 Pair 類別是什麼?
C# 中的 Pair 類別是一種簡單的資料結構,用於儲存兩個相關的值。它允許直接存取其屬性(作為公共欄位),因此在封裝並非首要考慮因素時,它是元組的便捷替代方案。
C# 中的 Pair 類別與 Tuple 類別有何不同?
Pair 類別與 Tuple 類別的差異在於,Pair 類別透過公共欄位直接暴露物件引用,從而增強了可讀性和靈活性。而 Tuple 類別是不可變的,只能透過Item1和Item2等屬性存取其元素。
使用 Pair 類別相比元組有哪些優勢?
與元組相比,使用 Pair 類別的優點包括:透過使用描述性的屬性名稱而不是Item1和Item2來提高程式碼可讀性,以及由於 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 庫透過 Pair 提供高效的資料結構管理,並透過 IronPDF 提供可靠的文件產生功能,增強了開發人員的工具包,使其在處理複雜的資料和文件工作流程方面具有價值。







