.NET幫助 C# 字典 Trygetvalue(開發者的工作原理) Curtis Chau 更新日期:7月 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 中的鍵是唯一的。 您可以訪問鍵來獲取對應的值,使 Dictionaries 在查詢功能上非常高效。 常規方法:ContainsKey 方法 在使用 C# Dictionaries 時,一個常見的任務是提取與特定鍵相關聯的值。 但是,直接訪問不存在的鍵可能會引發 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 方法檢查 “Alice” 是否是 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 is 20 years old.” 如果您試圖獲取不在 Dictionary 中的學生的年齡,ContainsKey 方法將阻止拋出 KeyNotFoundException,而是打印一條信息,表明該學生不存在。 然而,儘管 ContainsKey 方法很有用,它並不總是最有效的,因為在 Dictionary 上進行了兩次查詢操作:一個是 ContainsKey 方法,另一個是提取值。 這可能會耗時,特別是當處理大型 Dictionaries 時。 雖然 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 關鍵字用來表示此方法將更改 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 $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。 如果找到鍵,它將對應的值分配給 value 變量(學生名字),而該方法返回 true。 然後,程式打印出,“The name of the student with ID 2 is Bob.” 如果 TryGetValue 方法未找到鍵 2,它將默認的字符串值(即 null)分配給 value 變量,而該方法將返回 false。 然後代碼轉到 else 區塊,打印出“Dictionary 中不存在 ID 為 2 的學生。” TryGetValue 通過將鍵存在性檢查和值提取結合為一步簡化了您的代碼。此外,特別是面對更大的 Dictionarie,因為消除了多次鍵查找操作,提供了性能提升。 介紹 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 文件,編輯和提取 PDF 內容的 C# 庫。 使用 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 $vbLabelText $csharpLabel 在我們的主題背景下,想像一個從 Dictionary 檢索學生數據並想要生成 PDF 報告的場景。 TryGetValue 可以有效地提取必要的數據,然後利用 IronPDF 創建 PDF 文檔。 IronXL 探索 IronXL 用於 Excel 互動 是一個用於 C# 和 .NET 的 Excel 庫。 它使開發者能夠在 .NET 應用程序中讀取、寫入和創建 Excel 文件,無需 Interop。它非常適合需要從 Excel 電子表格中導出或導入數據的場景。 關於 TryGetValue,假設您有一個 Dictionary,其中鍵代表產品 ID,值代表它們的數量。 您可以使用 TryGetValue 來檢索特定產品的數量,然後使用 IronXL 在 Excel 庫存管理電子表格中更新該數量。 IronOCR 釋放 IronOCR 的文字識別之力 是一個用於 .NET 和 C# 的高級光學字符識別(OCR)和條碼讀取庫。 它允許開發者從圖像和 PDF 中讀取文本和條碼至 .NET 應用程序中。 這特別有用,當您需要從掃描的文檔或圖像中提取數據並在代碼中使用它時。 考慮一個場景,您使用 IronOCR 從掃描文檔中提取學生 ID。 處理後,您將 ID 和對應的學生詳細信息存儲在 Dictionary 中。 在檢索特定學生的詳細信息時,可以使用 TryGetValue 以有效地從 Dictionary 中提取數據。 IronBarcode 了解 IronBarcode 的條碼解決方案 是一個用於 .NET 的條碼讀取和寫作庫。 使用 IronBarcode,開發者可以生成和讀取各種條碼和二維碼格式。 這是一個強大的工具,用於以緊湊的機器可讀格式編碼和解碼數據。 在實際場景中,假設您使用條碼將產品信息存儲在零售系統中。 每個條碼可能對應於存儲為 Dictionary 中鍵的唯一產品 ID。 當條碼被掃描時,您可以使用 TryGetValue 來快速從 Dictionary 中提取並顯示相關的產品詳細信息。 結論 在我們探討了將 Iron 庫及其與標準 C# 功能如 TryGetValue 方法結合起來的功能時,很明顯這些工具能顯著提升您的開發過程。 無論您是處理 PDF、Excel 文件、OCR 還是條碼,Iron Suite 有一個針對您需求的解決方案。 更吸引人的是,這些產品中的每一個都提供 Iron Software 產品的免費試用,允許您探索和試驗其功能而無需任何費用。如果您決定繼續使用這些庫,許可從每個產品 $799 開始。 然而,如果您對多個 Iron 庫感興趣,在購買全套 Iron Suite 時可獲得更多價值,其價格僅相當於兩個單獨產品。 常見問題解答 TryGetValue 方法如何改善 C# 應用程式的性能? TryGetValue 方法將鍵驗證和值檢索合併為一個操作,從而提高性能。這減少了多次查找的需求,提高了效率,尤其是在處理大型數據集時。 ContainsKey 和 TryGetValue 方法在 C# 中有何不同? 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 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。 相關文章 更新日期 9月 4, 2025 RandomNumberGenerator C# 使用RandomNumberGenerator C#類可以幫助將您的PDF生成和編輯項目提升至新水準 閱讀更多 更新日期 9月 4, 2025 C#字符串等於(它如何對開發者起作用) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 更新日期 8月 5, 2025 C#開關模式匹配(對開發者來說是如何工作的) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 C# 預設參數(開發者的工作原理)C# 四捨五入(開發者的工...