.NET幫助 C# Pair Class(對於開發者的運行原理) Jacob Mellor 更新:2025年7月28日 下載 IronPDF NuGet 下載 DLL 下載 Windows 安裝程式 開始免費試用 LLM副本 LLM副本 將頁面複製為 Markdown 格式,用於 LLMs 在 ChatGPT 中打開 請向 ChatGPT 諮詢此頁面 在雙子座打開 請向 Gemini 詢問此頁面 在 Grok 中打開 向 Grok 詢問此頁面 打開困惑 向 Perplexity 詢問有關此頁面的信息 分享 在 Facebook 上分享 分享到 X(Twitter) 在 LinkedIn 上分享 複製連結 電子郵件文章 一對是一種簡單的資料結構,保存兩個相關的值。 它提供了一種方便的方法來將兩個不同的資料打包在一起。 當方法需要返回兩個值或處理鍵值關聯時,通常會使用對。 在C#中,開發人員經常使用元組 (Tuple<T1, T2>) 來配對值。 然而,元組是不可變的,其元素是通過如 Item1 和 Item2 的屬性訪問的,當大量使用時可能導致代碼可讀性降低。 這時,自定義的Pair類就派上用場。 如果您需要一個結構來保存兩個相關的對象,而數據隱藏不是重點時,您可以在代碼中使用Pair類。 Pair類不封裝其對象引用。 相反,它將它們直接暴露給所有調用代碼作為公共類欄。 這種設計選擇允許對內含對象的簡單訪問,而無需覆蓋封裝的開銷。 此外,在文章的結尾,我們將探討如何利用IronPDF for PDF Generation 從Iron Software Overview生成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}"); $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}"); $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}"); $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); $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; } } $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}"); $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}"); $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}"); $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 } }; $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"]}"); $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}"); } $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."); } $vbLabelText $csharpLabel 移除條目 // 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" } }; $vbLabelText $csharpLabel 超越字典:替代方案和考慮 雖然 Dictionary<TKey, TValue> 是強大的工具,但替代方法和考慮取決於您的應用程序的特定需求: ConcurrentDictionary<TKey, TValue>: 如果您的應用程序需要從多個執行緒對字典進行線程安全訪問,考慮使用 ConcurrentDictionary<TKey, TValue>。 ImmutableDictionary<TKey, TValue>: 若情境需要不可變性,來自 System.Collections.Immutable 命名空間的 ImmutableDictionary<TKey, TValue> 提供不可變鍵值集合。 自定義鍵值對類:當需要附加功能或特定行為時,考慮創建適合您需求的自定義鍵值對類。 IronPDF 程式庫 Iron Software 產品中的 IronPDF 是生成 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"); } } $vbLabelText $csharpLabel IronPDF 可以從 NuGet 包管理器中安裝: Install-Package IronPdf 或者這樣從 Visual Studio 安裝: 要生成包含元組範例的文件,我們可以使用以下代碼: 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); } } } $vbLabelText $csharpLabel 輸出 IronPDF 試用授權 獲取您的 IronPDF 試用授權 並將授權放在 appsettings.json。 { "IronPdf.LicenseKey": "<Your Key>" } 結論 在本文中,我們探討了對的概念與在C#中擁有一個 Pair 類的必要性。 我們提供了一個簡單的 Pair 自定義類執行,並提供了各種用例,展示它在日常程式設計任務中的多樣性和實用性。 無論您是在處理坐標、從方法返回多個值,還是儲存鍵值關聯,Pair類都可以是您程式設計能力的寶貴補充。 此外,IronPDF 程式庫功能 是開發人員在應用程式中按需快速生成 PDF 文件的絕佳組合技能。 常見問題解答 什麼是 C# 中的 Pair 類別? C# 中的 Pair 類別是一種設計用來保存兩個相關值的簡單數據結構。當封裝不是優先事項時,它允許通過公有字段直接訪問其屬性,是元組方便的替代方案。 Pair 類別與 C# 中的 Tuple 有何不同? Pair類與Tuple的區別在於,它通過公共字段直接暴露其對象引用,提高了可讀性和靈活性。另一方面,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 庫通過提供 Pairs 的有效數據結構管理和 IronPDF 的可靠文檔生成能力,提升了開發人員的工具箱,使其對於處理複雜數據和文檔工作流程非常有價值。 Jacob Mellor 立即與工程團隊聊天 首席技術官 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技術的創新,同時指導下一代技術領導者。 相關文章 更新2026年2月20日 銜接 CLI 簡化與 .NET : 使用 Curl DotNet 與 IronPDF for .NET Jacob Mellor 藉由 CurlDotNet 彌補了這方面的不足,CurlDotNet 是為了讓 .NET 生態系統能熟悉 cURL 而建立的函式庫。 閱讀更多 更新2025年12月20日 RandomNumberGenerator C# 使用RandomNumberGenerator C#類可以幫助將您的PDF生成和編輯項目提升至新水準 閱讀更多 更新2025年12月20日 C#字符串等於(它如何對開發者起作用) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 Internal Keyword C#(對於開發者的運行原理)Dapper C#(對於開發者的運...
更新2026年2月20日 銜接 CLI 簡化與 .NET : 使用 Curl DotNet 與 IronPDF for .NET Jacob Mellor 藉由 CurlDotNet 彌補了這方面的不足,CurlDotNet 是為了讓 .NET 生態系統能熟悉 cURL 而建立的函式庫。 閱讀更多