IRONSOFTWAREHOME
開發者更新

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

Jacob Mellor, Chief Technology Officer @ Team Iron
Jacob Mellor
Updated: 2026年4月23日

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

在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}");

元組的優勢

簡潔語法

元組允許您使用簡潔的語法來表示複雜的資料結構,而無需定義自定義類別或結構。

輕量級

元組是輕量級的資料結構,使其適合用於需要臨時或中間性資料儲存的情境。

隱式命名

使用元組語法時,您可以隱式命名元組元素,增強了程式碼的可讀性,減少了對註解的需求。

從方法返回多個值

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}");

將相關資料分組

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

限制與考量

雖然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;
    }
}

在這個類別中,型別在使用時定義,兩個屬性作為公共屬性公開。

使用 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}");

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}");

3. 儲存鍵值對

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

C#中的 Dictionary<TKey, TValue> 類是一個通用集合,用於儲存鍵值對。 它提供了基於鍵的快速查找,是管理關聯資料的常用工具。

建立和填充字典

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"]}");

遍歷鍵值對

// 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.");
}

移除條目

// 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" }
};

超越字典:選擇與考量

雖然 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");
    }
}

IronPDF 可以從 NuGet 套件管理器安裝:

PM > 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);
        }
    }
}

輸出

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

IronPDF 試用授權

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

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

結論

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

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

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

Jacob Mellor, Chief Technology Officer @ Team Iron
Chief Technology Officer

Jacob Mellor is Chief Technology Officer at Iron Software and a visionary engineer pioneering C# PDF technology. As the original developer behind Iron Software's core codebase, he has shaped the company's product architecture since its inception, transforming it alongside CEO Cameron Rimington into a 50+ person company serving NASA, Tesla, and global government agencies.

...
Read More

Related Articles

Key in blue circle

立即免費取得 30 天試用金鑰

bullet_checked無需信用卡或建立帳號
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
預訂您的免費現場演示
Booking Badge related to IronPDF Product Demo

受到全球數百萬工程師的信任

Iron Software的客戶標誌
獲取您的無義務諮詢
填寫以下表格或電子郵件sales@ironsoftware.com
您的詳細資訊將始終保密
受到全球數百萬工程師的信任
Iron Software的客戶標誌
立即獲取您的30天試用金鑰
無需信用卡或帳戶建立