.NET 帮助 C# Pair类(开发人员如何使用) 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 进行 PDF 生成 来生成 PDF 文档,这来自 Iron Software 概览。 元组 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>。 ImmutableDictionary<TKey, TValue>提供了不可变的键值集合。 自定义键值对类:在需要额外功能或特定行为的情况下,考虑创建自定义键值对类以满足您的需求。 IronPDF库 Iron Software产品的IronPDF 是一个用于生成PDF文档的优秀库。 它的易用性和高效性无与伦比。 IronPDF在HTML到PDF转换方面表现出色,确保精确保留原始布局和样式。 它非常适合从基于Web的内容中创建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 可以从NuGet包管理器安装IronPDF: 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# 中的元组有何不同? Pair 类与元组的不同之处在于它通过公共字段直接暴露其对象引用,增强了可读性和灵活性。而元组是不可变的,通过像 Item1 和 Item2 这样的属性访问其元素。 使用 Pair 类相对于元组的优势是什么? 使用 Pair 类相对于元组的优势包括使用描述性的属性名称而不是 Item1 和 Item2 来提高代码可读性,并且可以修改值,因为 Pairs 是可变的。 我可以使用 Pair 类来存储键值对吗? 是的,Pair 类特别适用于以比元组更具可读性的方式存储键值对,因为它可以通过公共字段直接访问值。 使用 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 核心代码库的原始开发者,他从公司成立之初就开始塑造公司的产品架构,与首席执行官 Cameron Rimington 一起将公司转变为一家拥有 50 多名员工的公司,为 NASA、特斯拉和全球政府机构提供服务。Jacob 拥有曼彻斯特大学土木工程一级荣誉工程学士学位(BEng)(1998-2001 年)。他的旗舰产品 IronPDF 和 Iron Suite for .NET 库在全球的 NuGet 安装量已超过 3000 万次,其基础代码继续为全球使用的开发人员工具提供动力。Jacob 拥有 25 年的商业经验和 41 年的编码专业知识,他一直专注于推动企业级 C#、Java 和 Python PDF 技术的创新,同时指导下一代技术领导者。 相关文章 已更新2026年2月20日 架起 CLI 简洁性与 .NET 的桥梁:使用 IronPDF for .NET 的 Curl DotNet Jacob Mellor 通过 CurlDotNet 填补了这一空白,CurlDotNet 库的创建是为了将 cURL 的熟悉感带入 .NET 生态系统。 阅读更多 已更新2025年12月20日 RandomNumberGenerator C# 使用 RandomNumberGenerator C# 类可以帮助将您的 PDF 生成和编辑项目提升到一个新的高度。 阅读更多 已更新2025年12月20日 C# String Equals(开发者用法) 与强大的 PDF 库 IronPDF 结合使用,切换模式匹配允许您为文档处理构建更智能、更简洁的逻辑。 阅读更多 C# Internal关键字(开发人员如何使用)Dapper C#(开发者如何使用)
已更新2026年2月20日 架起 CLI 简洁性与 .NET 的桥梁:使用 IronPDF for .NET 的 Curl DotNet Jacob Mellor 通过 CurlDotNet 填补了这一空白,CurlDotNet 库的创建是为了将 cURL 的熟悉感带入 .NET 生态系统。 阅读更多
已更新2025年12月20日 RandomNumberGenerator C# 使用 RandomNumberGenerator C# 类可以帮助将您的 PDF 生成和编辑项目提升到一个新的高度。 阅读更多