.NET 帮助 C# 字典 Trygetvalue(开发者如何使用) 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# 是一种多功能且强大的语言,提供了许多功能。 其中之一是 C# Dictionary。 理解 C# Dictionary 的基础 在深入探讨 TryGetValue 方法之前,很重要的是要理解 C# 中的 Dictionary 是什么。 简单来说,Dictionary 是一个键/值对的集合。 例如,您可能有一个 Dictionary,其中键是学生的姓名(字符串值),而值是他们相应的年龄(整数值)。 Dictionary<string, int> studentAges = new Dictionary<string, int> { {"Alice", 20}, {"Bob", 22}, {"Charlie", 19} }; Dictionary<string, int> studentAges = new Dictionary<string, int> { {"Alice", 20}, {"Bob", 22}, {"Charlie", 19} }; Dim studentAges As New Dictionary(Of String, Integer) From { {"Alice", 20}, {"Bob", 22}, {"Charlie", 19} } $vbLabelText $csharpLabel Dictionary 中的键是唯一的。 您可以访问键以获取相应的值,这使得 Dictionary 在查找功能上非常高效。 传统方法:ContainsKey 方法 在处理 C# Dictionary 时,一个常见的任务是获取与特定键关联的值。 然而,直接访问不存在的键可能会抛出 KeyNotFoundException,中断程序的流程。 为了避免这种情况,通常的做法是在 Dictionary 中检查指定的键是否存在。 这就是 ContainsKey 方法的用武之地。 ContainsKey 方法是一种简单而直观的函数,用于检查某个键是否存在于 Dictionary 中。 以下是 ContainsKey 方法的基本语法: Dictionary<TKey, TValue>.ContainsKey(TKey key) Dictionary<TKey, TValue>.ContainsKey(TKey key) 'INSTANT VB TODO TASK: The following line uses invalid syntax: 'Dictionary<TKey, TValue>.ContainsKey(TKey key) $vbLabelText $csharpLabel 它将键作为参数并返回一个布尔值。 如果键在 Dictionary 中,它将返回 true; 如果不在,它将返回 false。 考虑以下示例,其中我们有一个以学生姓名为键,其对应年龄为值的 Dictionary。 Dictionary<string, int> studentAges = new Dictionary<string, int> { {"Alice", 20}, {"Bob", 22}, {"Charlie", 19} }; Dictionary<string, int> studentAges = new Dictionary<string, int> { {"Alice", 20}, {"Bob", 22}, {"Charlie", 19} }; Dim studentAges As New Dictionary(Of String, Integer) From { {"Alice", 20}, {"Bob", 22}, {"Charlie", 19} } $vbLabelText $csharpLabel 现在,如果您想获取名为“爱丽丝”(Alice)的学生的年龄,您将首先使用 ContainsKey 方法来检查“爱丽丝”是否是 Dictionary 中的一个键。 string student = "Alice"; if (studentAges.ContainsKey(student)) { int age = studentAges[student]; Console.WriteLine($"{student} is {age} years old."); } else { Console.WriteLine($"{student} does not exist in the dictionary."); } string student = "Alice"; if (studentAges.ContainsKey(student)) { int age = studentAges[student]; Console.WriteLine($"{student} is {age} years old."); } else { Console.WriteLine($"{student} does not exist in the dictionary."); } Dim student As String = "Alice" If studentAges.ContainsKey(student) Then Dim age As Integer = studentAges(student) Console.WriteLine($"{student} is {age} years old.") Else Console.WriteLine($"{student} does not exist in the dictionary.") End If $vbLabelText $csharpLabel 在这种情况下,程序将打印“爱丽丝(Alice)20岁”。如果您尝试获取不存在于 Dictionary 中的学生的年龄,ContainsKey 方法将防止抛出 KeyNotFoundException,而是打印学生不存在的消息。 然而,虽然 ContainsKey 方法可能很有用,但它并不总是最高效的,因为在 Dictionary 上执行了两次查找操作:一次用于 ContainsKey 方法,一次用于检索值。 这可能会消耗时间,尤其是在处理大型 Dictionary 时。 虽然 ContainsKey 方法是处理 Dictionary 中找不到指定键时异常的简单而直观的方法,但值得考虑诸如 TryGetValue 之类的替代方法,这些方法可以以更好的性能实现相似的功能。 我们将在以下章节中更详细地讨论 TryGetValue。 使用 TryGetValue 进行验证和检索的结合 TryGetValue 方法就是在这里发挥作用的。 TryGetValue 方法将验证和值检索结合在一个步骤中,提供了几乎相同的代码功能但具有更好的性能。 TryGetValue 方法需要两个参数: 您要查找的键。 一个 out 参数,如果键存在,将保存该键的值。 语法如下: Dictionary<TKey, TValue>.TryGetValue(TKey key, out TValue value) Dictionary<TKey, TValue>.TryGetValue(TKey key, out TValue value) 'INSTANT VB TODO TASK: The following line uses invalid syntax: 'Dictionary<TKey, TValue>.TryGetValue(TKey key, out TValue value) $vbLabelText $csharpLabel out 关键字用于表示此方法将更改 值 参数。 如果找不到指定的键,out 值将为值类型的默认值(整数为 0,引用类型为 null)。 否则,它将保存与提供的键相对应的值。 以下是如何使用 TryGetValue: string student = "Alice"; if (studentAges.TryGetValue(student, out int age)) { Console.WriteLine($"{student} is {age} years old."); } else { Console.WriteLine($"{student} does not exist in the dictionary."); } string student = "Alice"; if (studentAges.TryGetValue(student, out int age)) { Console.WriteLine($"{student} is {age} years old."); } else { Console.WriteLine($"{student} does not exist in the dictionary."); } Dim student As String = "Alice" Dim age As Integer If studentAges.TryGetValue(student, age) Then Console.WriteLine($"{student} is {age} years old.") Else Console.WriteLine($"{student} does not exist in the dictionary.") End If $vbLabelText $csharpLabel 此代码提供了几乎与 ContainsKey 方法示例相同的功能,但更高效,因为它仅查找一次键。 TryGetValue 操作代码示例 为了更好地理解 TryGetValue 方法,让我们探索一个实际的代码示例。 考虑一个学校数据库,其中每个学生都有一个唯一的 ID 和相应的名字。 这些数据存储在一个以学生 ID 为键,名字为值的 Dictionary 中。 Dictionary<int, string> studentNames = new Dictionary<int, string> { {1, "Alice"}, {2, "Bob"}, {3, "Charlie"} }; Dictionary<int, string> studentNames = new Dictionary<int, string> { {1, "Alice"}, {2, "Bob"}, {3, "Charlie"} }; Dim studentNames As New Dictionary(Of Integer, String) From { {1, "Alice"}, {2, "Bob"}, {3, "Charlie"} } $vbLabelText $csharpLabel 在这种情况下,假设您想检索 ID 为 2 的学生的名字,但您也希望确保该 ID 的学生存在于数据库中。 传统上,您可能首先使用 ContainsKey 方法检查键(学生 ID 2)是否存在,然后访问 Dictionary 获取相应的值(学生名)。 然而,使用 TryGetValue 方法,您可以在一个步骤中完成这一操作。 TryGetValue 方法需要两个参数:您要查找的键和一个 out 参数,如果该键存在,它将保存与该键相关联的值。 如果找到键,方法将返回 true,并将相应的值分配给 out 参数。 如果没有,它将返回 false,out 参数将采用其类型的默认值。 int i = 2; // Student ID if (studentNames.TryGetValue(i, out string value)) { Console.WriteLine($"The name of the student with ID {i} is {value}."); } else { Console.WriteLine($"No student with ID {i} exists in the dictionary."); } int i = 2; // Student ID if (studentNames.TryGetValue(i, out string value)) { Console.WriteLine($"The name of the student with ID {i} is {value}."); } else { Console.WriteLine($"No student with ID {i} exists in the dictionary."); } Dim i As Integer = 2 ' Student ID Dim value As String If studentNames.TryGetValue(i, value) Then Console.WriteLine($"The name of the student with ID {i} is {value}.") Else Console.WriteLine($"No student with ID {i} exists in the dictionary.") End If $vbLabelText $csharpLabel 在这种情况下,TryGetValue 方法在 studentNames Dictionary 中查找键 2。 如果找到键,它将相应的值分配给 值 变量(学生名字),并且方法返回 true。 然后,程序打印出“ID 为 2 的学生名字是 Bob。” 如果 TryGetValue 方法找不到键 2,它将把默认字符串值(即 null)分配给 值 变量,并且方法将返回 false。 代码然后进入 else 块,打印出“在字典中不存在 ID 为 2 的学生。” TryGetValue 通过将键存在检查和值检索合并为一步来简化您的代码。此外,通过消除了多次键查找操作,它提供了特别是对于较大 Dictionary 的性能提升。 介绍 Iron Suite 随着您在 C# 旅程中不断进步,您将发现许多工具和库可以显著增强您的编程能力。 其中包括 Iron 库,一套专门设计用于扩展 C# 应用程序功能的工具。 它们包括 IronPDF, IronXL, IronOCR 和 IronBarcode。 每个库都有一套独特的功能,它们都在与标准 C# 一起使用时提供了显著优势。 IronPDF。 Discover IronPDF for PDF Creation in .NET is a C# library designed to 从 HTML 创建 PDF 文件,编辑和提取 .NET 应用程序中的 PDF 内容。 使用 IronPDF,您可以以编程方式生成 PDF 报告,填写 PDF 表单并处理 PDF 文档。 该库还提供 HTML 转 PDF 的功能,使得将现有 HTML 内容转换为 PDF 变得容易。 IronPDF 的亮点是其 HTML 转 PDF 功能,保持所有布局和样式完整。 它允许您从网络内容创建 PDF,适用于报告、发票和文档。 下面是一个简化示例,演示了如何在 CQRS 设置中使用 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 在我们的话题背景下,想象一下您正在从 Dictionary 中检索学生数据并想要生成 PDF 报告的场景。 TryGetValue 可以高效地获取必要数据,然后利用 IronPDF 创建 PDF 文档。 了解更多关于 IronXL 是一个 Excel 库,可帮助处理 Excel 文件而无需安装 Excel。 探索 IronXL 进行 Excel 互动 是一个用于 C# 和 .NET 的 Excel 库。 它使开发者能够在 .NET 应用程序中读、写和创建 Excel 文件,而无需 Interop。这对于需要从 Excel 电子表格导出或导入数据的场景非常理想。 关于 TryGetValue,假设您有一个以产品 ID 为键,数量为值的 Dictionary。 您可以使用 TryGetValue 获取特定产品的数量,然后使用 IronXL 更新 Excel 库存管理电子表格中的数量。 光学字符识别 (OCR) 是一种将不同类型的文档转换为可编辑和可搜索数据的技术。 释放 IronOCR 的文本识别能力 是一个高级的用于 .NET 和 C# 的 OCR(光学字符识别)和条码读取库。 它允许开发者在 .NET 应用程序中从图像和 PDF 中读取文本和条码。 当您需要从扫描文档或图像中提取数据并在代码中处理时,这尤其有用。 考虑一个场景,您已使用 IronOCR 从扫描文档中提取了学生 ID。 处理后,您将 ID 和相应的学生详细信息存储在一个 Dictionary 中。 在检索特定学生的详细信息时,TryGetValue 可用于高效地从 Dictionary 中获取数据。 开始使用 IronBarcode 是一个专为 .NET 框架设计的条码读取和写入库。 了解 IronBarcode 的条码解决方案 是一个用于 .NET 的条码读取和写入库。 通过 IronBarcode,开发者可以生成和读取各种条码和 QR 码格式。 这是编码和解码数据的强大工具,格式紧凑且易于机器读取。 在实际场景中,假设您正在使用条码来存储零售系统中的产品信息。 每个条码可以对应一个存储为 Dictionary 键的唯一产品 ID。 当扫描条码时,您可以使用 TryGetValue 快速从 Dictionary 中获取并显示相关的产品详细信息。 结论 随着我们在 Iron 库与标准 C# 功能结合的探索中,功能如 TryGetValue,可以明显增强您的开发流程。 无论您是在处理 PDF、Excel 文件、OCR 还是条码,Iron Suite 都有针对您的需求量身定制的解决方案。 更吸引人的是,这些产品中的每一个都提供 Iron Software 产品的免费试用,允许您免费探索和试验这些功能。如果您打算继续使用这些库,许可证从每个产品的 $799 开始。 但是,如果您对多个 Iron 库感兴趣,还有更多的价值,因为您可以以两个单独产品的价格购买完整的 Iron Suite。 常见问题解答 TryGetValue方法如何提高C#应用程序的性能? TryGetValue方法通过将键验证和值检索合并为一个操作来提高性能。这减少了多次查找的需要,尤其在处理大型数据集时提高了效率。 C#中的ContainsKey和TryGetValue方法之间的区别是什么? ContainsKey在不检索值的情况下检查键是否存在,而TryGetValue在一个步骤中检查键的存在并检索值,使其更高效。 可以将Iron库与C#字典操作集成吗? 是的,像IronPDF、IronXL、IronOCR和IronBarcode这样的Iron库可以与C#字典操作集成以增强应用程序。例如,TryGetValue可以在使用IronPDF生成动态报告时高效管理数据。 IronPDF如何在.NET应用程序中改进文档生成? IronPDF允许从HTML创建、编辑和转换PDF,保持文档的布局和风格。它在程序化地生成报告、发票和其他文档时特别有用,适用于.NET应用程序。 在C#中使用IronXL进行电子表格管理的好处是什么? IronXL提供了读取、写入和创建Excel文件的功能,无需Interop,是.NET应用程序中的数据导出和导入任务的理想选择。 IronOCR如何在C#应用程序中实现数据提取? IronOCR能够从图像和PDF中提取文本和条形码,使其在处理扫描文档并将提取的数据集成到C#应用程序中时极其有用。 IronBarcode库在C#开发中扮演什么角色? IronBarcode允许生成和读取条形码和QR码,提供了一种对数据进行编码和解码的机器可读形式,这对于库存管理及其他C#应用程序至关重要。 为什么开发人员应该在他们的C#项目中使用Iron Suite? Iron Suite提供了一套全面的工具,用于PDF、Excel、OCR和条形码功能,从而增强了开发人员在C#应用程序中有效处理广泛任务的能力。 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# 默认参数(开发者如何使用)C# Round(开发者如何使用)
已更新九月 4, 2025 RandomNumberGenerator C# 使用 RandomNumberGenerator C# 类可以帮助将您的 PDF 生成和编辑项目提升到一个新的高度。 阅读更多