C# 字典 Trygetvalue(開發者的工作原理)
C# 是一種多用途且功能強大的語言,可提供許多功能。 其中包括 C# 詞典。
瞭解 C# 辭典的基礎知識
在深入了解 TryGetValue 方法之前,了解 C# 中的 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}
}詞典中的鍵是唯一的。 您可以存取鍵來取得相對應的值,這使得 Dictionaries 在查詢功能上有難以置信的效率。
傳統方法:ContainsKey 方法。
在使用 C# 字典時,常見的任務是取得與特定鍵相關的值。 然而,直接存取不存在的鍵可能會產生 KeyNotFoundException,中斷您的程式流程。 為了避免這種情況,通常的做法是檢查字典中是否存在指定的關鍵字。 這就是 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)它將關鍵字作為參數,並返回一個布林值。 如果關鍵字在辭典中,則會返回 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"。如果您嘗試取得 Dictionary 中不存在的學生年齡,ContainsKey 方法將防止產生 KeyNotFoundException 並取代列印學生不存在的訊息。
然而,雖然 ContainsKey 方法很有用,但它並不總是最有效率的方法,因為要對 Dictionary 執行兩個查詢作業:一個用於 ContainsKey 方法,另一個用於擷取值。 這可能很花時間,尤其是在處理大型字典時。
雖然 ContainsKey 方法是一種簡單直觀的方式,可以在 Dictionary 中找不到指定的 key 時處理異常,但值得考慮其他方法,例如 TryGetValue 方法,它可以以更好的效能達到類似功能。 我們將在以下章節中詳細討論 TryGetValue 。
使用 TryGetValue 來結合驗證與擷取。
這就是 TryGetValue 方法派上用場的地方。 TryGetValue 方法將驗證和值擷取結合在單一步驟中,提供幾乎相同的程式碼功能,但效能更強。
TryGetValue 方法需要兩個參數:
1.您正在尋找的關鍵 2.一個 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 參數。 如果找不到指定的 key,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 和相對應的姓名。 這些資料儲存在以學生 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 方法檢查關鍵 (student 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 透過將按鍵存在性檢查和值擷取結合為單一步驟,簡化您的程式碼。此外,它還提供了效能提升,尤其是對於較大的辭典,因為它省去了多重鍵查詢的操作。
介紹 Iron Suite
當您在 C# 的旅程中不斷進步時,您會發現有許多工具和函式庫可供您使用,可以大幅提升您的程式設計能力。 其中 Iron library 是一套專門用來擴充 C# 應用程式功能的工具。 這些工具包括 IronPDF、IronXL、IronOCR 和 IronBarcode。 這些函式庫都有其獨特的功能,當與標準 C# 結合使用時,它們都能提供顯著的優勢。
IronPDF。

Discover IronPDF for PDF Creation in .NET 是一個 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。

Explore IronXL for Excel Interactions 是適用於 C# 和 .NET 的 Excel 函式庫。 它可讓開發人員在 .NET 應用程式中讀取、寫入和建立 Excel 檔案,而無需 Interop。它非常適合需要從 Excel 試算表匯出或匯入資料的情況。
關於 TryGetValue, 假設您有一個 Dictionary,其中 keys 代表產品 ID,而 values 代表它們的數量。 您可以使用 TryGetValue 檢索特定產品的數量,然後在 Excel 存貨管理試算表中使用 IronXL 更新該數量。
IronOCR。

Unleash the Power of IronOCR for Text Recognition 是用於 .NET 和 C# 的先進 OCR(光學字元辨識)和 BarCode 閱讀函式庫。 它可讓開發人員在 .NET 應用程式中讀取影像和 PDF 中的文字和 BarCode。 當您需要從掃描的文件或影像中擷取資料,並在程式碼中處理時,這可能會特別有用。
考慮一個您使用 IronOCR 從掃描文件中擷取學生 ID 的情境。 處理完成後,您會將 ID 和對應的學生詳細資料儲存在辭典中。 在擷取特定學生的詳細資料時,可使用 TryGetValue 來有效率地從字典中擷取資料。
IronBarcode。

Learn About IronBarcode for Barcode Solutions 是 .NET 的条码读写库。 透過 IronBarcode,開發人員可以產生和讀取各種條碼和 QR 代碼格式。 它是以精簡、機器可讀的格式對資料進行編碼和解碼的強大工具。
在實際的情境中,想像您在零售系統中使用 BarCode 儲存產品資訊。 每個 BarCode 都可以對應到一個獨特的產品 ID,並儲存為辭典中的關鍵字。 當掃描 BarCode 時,您可以使用 TryGetValue 快速地從字典中取得並顯示相關產品的詳細資訊。
結論
當我們結合標準 C# 功能 (例如 TryGetValue 方法) 探索 Iron 函式庫的功能時,很明顯這些工具可以大幅提升您的開發流程。 無論您是處理 PDF、Excel 檔案、OCR 或 BarCode,Iron Suite 都有為您量身打造的解決方案。
更吸引人的是,每一個產品都提供 免費試用 Iron Software 產品,讓您可以免費探索和實驗功能。如果您決定繼續使用這些函式庫,每項產品的授權起點為 $799 。 不過,如果您對多個 Iron 函式庫感興趣,還可以發現更多價值,因為您只需花兩個單獨產品的價格,就可以購買完整的 Iron Suite。
常見問題解答
TryGetValue 方法如何改善 C# 應用程式的效能?
TryGetValue 方法將金鑰驗證與值擷取合併為單一操作,以改善效能。這可減少多次查詢的需求並提高效率,尤其是在處理大型資料集時。
C# 中的 ContainsKey 與 TryGetValue 方法有何差異?
ContainsKey 會檢查字典中是否存在關鍵,但不會擷取其值,而 TryGetValue 會檢查關鍵是否存在,如果存在,則會擷取值,所有步驟只需一步,因此更有效率。
Iron 函式庫能否與 C# 辭典作業整合?
是的,IronPdf、IronXL、IronOCR 和 IronBarcode 等 Iron 函式庫可以與 C# Dictionary 作業整合,以增強應用程式的功能。例如,在使用 IronPDF 產生動態報表時,可以使用 TryGetValue 來有效管理資料。
IronPDF 如何改善 .NET 應用程式中的文件生成?
IronPDF 允許從 HTML 建立、編輯和轉換 PDF,並維持文件的排版和樣式。它對於在 .NET 應用程式中以程式化方式產生報表、發票和其他文件特別有用。
在 C# 中使用 IronXL 進行試算表管理有哪些好處?
IronXL.Excel 提供讀取、寫入和建立 Excel 檔案的功能,不需要 Interop,因此非常適合 .NET 應用程式中的資料匯出和匯入工作。
IronOCR 如何促進 C# 應用程式中的資料擷取?
IronOCR 能夠從影像和 PDF 中萃取文字和 BarCode,使其可用於處理掃描的文件,並將萃取的資料整合至 C# 應用程式中。
IronBarcode 程式庫在 C# 開發中扮演什麼角色?
IronBarcode 可以生成和讀取條碼和 QR 代碼,提供了一種以機器可讀格式編碼和解碼資料的方法,這對庫存管理和其他 C# 應用程式非常重要。
開發人員為何要在 C# 專案中使用 Iron Suite?
Iron Suite 提供 PDF、Excel、OCR 和 BarCode 功能的全面工具集,可提高開發人員在 C# 應用程式中有效處理各種任務的能力。







