.NET 帮助 C# Pair类(开发人员如何使用) Curtis Chau 已更新:七月 28, 2025 Download IronPDF NuGet 下载 DLL 下载 Windows 安装程序 Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article 对。 它提供了一种将两个不同数据片段捆绑在一起的便捷方法。 当方法需要返回两个值或处理键值关联时,通常会使用成对。 在C#中,开发人员通常使用元组(Tuple<T1, T2>)进行值配对。 然而,元组是不可变的,其元素是通过Item1和Item2这样的属性访问的,这可能在大量使用时导致代码的可读性降低。 这就是自定义Pair类的用武之地。 如果您需要一个结构来保存两个相关对象且数据隐藏不是优先事项,您可以在代码中使用Pair类。 Pair类不会封装其对象引用。 相反,它将它们直接作为公共类字段暴露给所有调用代码。 这种设计选择允许无需封装开销即可简单直接地访问包含的对象。 Also, at the end of the article, we will explore how IronPDF for PDF Generation from Iron Software Overview can be used to generate a PDF document. 元组 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 元组的优点 简明的语法 元组允许您使用简明的语法表达复杂的数据结构,而无需定义自定义类或结构。 轻量级 元组是轻量级的数据结构,非常适用于需要临时或中间数据存储的场景。 隐式命名 通过元组语法,您可以隐式地命名元组元素,增加代码的可读性并减少对注释的需求。 从方法返回多个值 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元组提供了显著的优势,但仍需注意以下限制和注意事项: 与自定义类或结构相比,元组在表达能力上有限。 当没有提供显式名称时,元组元素通过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; } } 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类可以受益的常见用例: 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>在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>:对于需要不变性的场景,System.Collections.Immutable命名空间提供的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"); } } 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 可以从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); } } } 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 输出 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 的可靠文档生成功能,增强了开发者工具包,使其对处理复杂数据和文档工作流非常有价值。 Curtis Chau 立即与工程团队聊天 技术作家 Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。 相关文章 已更新九月 4, 2025 RandomNumberGenerator C# 使用 RandomNumberGenerator C# 类可以帮助将您的 PDF 生成和编辑项目提升到一个新的高度。 阅读更多 已更新九月 4, 2025 C# String Equals(开发者用法) 与强大的 PDF 库 IronPDF 结合使用,切换模式匹配允许您为文档处理构建更智能、更简洁的逻辑。 阅读更多 已更新八月 5, 2025 C# Switch 模式匹配(开发者用法) 与强大的 PDF 库 IronPDF 结合使用,切换模式匹配允许您为文档处理构建更智能、更简洁的逻辑。 阅读更多 C# Internal关键字(开发人员如何使用)Dapper C#(开发人员如何使用)
已更新九月 4, 2025 RandomNumberGenerator C# 使用 RandomNumberGenerator C# 类可以帮助将您的 PDF 生成和编辑项目提升到一个新的高度。 阅读更多