在生产环境中测试,无水印。
随时随地满足您的需求。
获得30天的全功能产品。
几分钟内就能启动并运行。
在您的产品试用期间,全面访问我们的支持工程团队。
C# 是一种多功能且强大的语言,提供了许多功能。 其中包括 C# Dictionary。
在深入了解TryGetValue
方法之前,首先需要理解C#中的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}
}
字典中的键是唯一的。 您可以访问键以获取相应的值,使得字典在查找功能方面非常高效。
ContainsKey
方法在处理 C# 字典时,一个常见的任务是获取与特定键相关的值。 然而,直接访问不存在的键可能会抛出KeyNotFoundException
,中断程序的流程。 为了避免这种情况,通常的做法是检查指定的键是否存在于字典中。 这就是 ContainsKey
方法发挥作用的地方。
ContainsKey
方法是一个简单直观的功能,用于检查特定键是否存在于字典中。 以下是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)
它将键作为参数并返回一个布尔值。 如果键在字典中,它将返回true
; 否则,它将返回false
。
请考虑以下示例:我们有一个字典,将学生姓名作为键,并将其对应的年龄作为值。
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}
}
现在,如果你想获取名为“Alice”的学生的年龄,你首先会使用ContainsKey
方法来检查“Alice”是否是词典中的一个键。
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
在这种情况下,程序将打印“Alice is 20 years old.” 如果您尝试获取字典中不存在的学生的年龄,ContainsKey
方法将防止抛出 KeyNotFoundException
,而是打印一条学生不存在的消息。
然而,虽然ContainsKey
方法可能是有用的,但它不总是最有效的。 在上面的代码片段中,字典上执行了两个查找操作:一个用于 ContainsKey
方法,一个用于检索值。 这可能会耗费时间,尤其是处理大型字典时。
虽然ContainsKey
方法是处理在字典中找不到指定键时异常的一种简单直观的方法,但值得考虑像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)
out
关键字用于表示此方法将更改 value
参数。 如果未找到指定键,则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
该代码提供了与ContainsKey
方法示例几乎相同的功能,但它更高效,因为它只查找一次键。
TryGetValue
在操作代码示例为了更好地理解TryGetValue
方法,让我们探讨一个实际的代码示例。 考虑一个学校数据库,每个学生都有一个唯一的ID和相应的姓名。 这些数据存储在一个Dictionary中,学生ID作为键,名字作为值。
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"}
}
在这种情况下,假设你想获取ID为2的学生的姓名,但你还想确保具有此ID的学生存在于数据库中。
传统上,您可能会首先使用ContainsKey
方法来检查键(学生ID 2)是否存在,然后访问字典以获取相应的值(学生姓名)。 然而,使用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
在这种情况下,TryGetValue
方法在 studentNames
字典中查找键 2。 如果找到键,则将相应的值分配给value
变量(学生的名字),并且该方法返回true
。 然后,程序打印出:“ID为2的学生的名字是Bob。”
如果TryGetValue
方法没有找到键2,它将把字符串的默认值(即null)赋给value
变量,并且该方法将返回false
。 然后代码进入else
块,输出“字典中不存在ID为2的学生。”
TryGetValue
通过将键存在检查和值检索合并为一个步骤,简化了您的代码。此外,它通过消除多次键查找操作,特别是在处理较大字典时,提供了性能提升。
随着你在C#编程旅程中不断进步,你会发现有许多工具和库可供使用,这些工具和库可以显著提升你的编程能力。 其中包括Iron库,这是一个专门设计用于扩展C#应用程序功能的工具套件。 它们包括 IronPDF、IronXL、IronOCR 和 IronBarcode。 这些库各自具有独特的功能,当与标准C#结合使用时,它们都能提供显著的优势。
探索适用于.NET的IronPDF进行PDF创建 是一个C#库,旨在在.NET应用程序中从HTML创建PDF文件、编辑和提取PDF内容。 通过IronPDF,您可以以编程方式生成PDF报告、填写PDF表单和操作PDF文档。 该库还提供HTML到PDF转换功能,使将现有的HTML内容转换为PDF变得容易。
IronPDF 的亮点是其HTML 转 PDF功能,能够保持所有布局和样式完好无损。 它允许您从网络内容创建PDF,适用于报告、发票和文档。 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");
}
}
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
在我们的主题背景下,想象一个从字典中检索学生数据并生成PDF报告的场景。 TryGetValue
可以高效获取必要的数据,然后利用 IronPDF 创建 PDF 文档。
探索IronXL的Excel交互功能 是一个用于C#和.NET的Excel库。 它使开发人员可以在 .NET 应用程序中读取、写入和创建 Excel 文件,无需 Interop。它非常适合需要从 Excel 电子表格导出或导入数据的场景。
关于TryGetValue
,假设您有一个字典,其中键代表产品ID,值代表它们的数量。 您可以使用TryGetValue
来检索特定产品的数量,然后使用IronXL在Excel库存管理电子表格中更新该数量。
释放IronOCR的文本识别功能是一个用于.NET和C#的高级OCR(光学字符识别)和条形码读取库。 它允许开发人员在 .NET 应用程序中读取图像和 PDF 中的文本和条形码。 当你需要从扫描文档或图像中提取数据并在代码中使用时,这可能特别有用。
考虑使用IronOCR从扫描文件中提取学生证号的情景。 处理后,您将ID和相应的学生详细信息存储在字典中。 在检索特定学生的详细信息时,可以使用TryGetValue
从Dictionary中有效地获取数据。
了解 IronBarcode for Barcode Solutions 是一个用于 .NET 的条形码读取和写入库。 使用IronBarcode,开发人员可以生成和读取各种条形码和二维码格式。 它是一种强大的工具,可以将数据编码和解码为紧凑的机器可读格式。
在实际应用中,想象您在零售系统中使用条形码存储产品信息。 每个条形码可以对应存储在字典中的一个唯一产品ID。 当扫描条形码时,您可以使用TryGetValue
从字典中快速获取并显示相关的产品详细信息。
随着我们研究了Iron库与标准C#功能(如TryGetValue
方法)的结合,很明显这些工具可以显著提升您的开发过程。 无论您是处理PDF、Excel文件、OCR,还是条形码,Iron Suite都有适合您的解决方案。
更具有吸引力的是,每个产品都提供Iron Software 产品的免费试用,让您可以零费用探索和试验这些功能。如果您决定继续使用这些库,每个产品的许可费用从$749起。 但是,如果您对多个Iron库感兴趣,可以以只购买两个独立产品的价格购买完整的Iron Suite,从而获得更多的价值。