在實際環境中測試
在生產環境中測試無浮水印。
在任何需要的地方都能運作。
C#是一種多功能且強大的語言,提供了許多功能。其中之一是C#字典。
在深入了解 TryGetValue
方法之前,理解 C# 中的字典是至關重要的。簡單來說,字典是一種鍵/值對的集合。例如,你可能擁有一個字典,其中的鍵是學生的名字 (字串值),這些值是他們相應的年齡 (整數值).
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
方法需要兩個參數:
你要尋找的鍵。
這裡是語法:
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 和對應的名字。這些數據存儲在一個以學生 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
方法來檢查鍵是否存在 (學生證號碼 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
。然後,程式會打印出 "The name of the student with ID 2 is Bob."。
如果 TryGetValue
方法沒有找到鍵 2,它將分配字串的預設值。 (為空) 將值賦予value
變數,並且該方法將返回false
。然後,代碼將進入else
塊,輸出「No student with ID 2 exists in the dictionary.」
TryGetValue
透過將鍵存在性檢查和值檢索合併為一步,來簡化你的代碼。此外,它通過消除多次鍵查詢操作,為較大的詞典提供了性能提升。
當你在 C# 的旅程中不斷進步時,會發現有許多工具和庫可以大大提升程式設計能力。其中包括 Iron 軟體庫,一套專門設計來擴展 C# 應用程式功能的工具套件。它們包括 IronPDF、IronXL、IronOCR 和 IronBarcode。這些庫各自具有獨特的功能,並且當與標準的 C# 結合使用時,都能提供顯著的優勢。
IronPDF 是一個設計用於C#的庫 從 HTML 創建 PDF 文件在 .NET 應用程式中編輯和提取 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 是一個用於 C# 和 .NET 的 Excel 函式庫。它使開發人員能夠在 .NET 應用程式中讀取、寫入和創建 Excel 文件,而不需使用 Interop。這非常適合需要從 Excel 試算表中導出或導入數據的情況。
關於 TryGetValue
,假設你有一個字典,其中的鍵代表產品 ID,值代表它們的數量。你可以使用 TryGetValue
來檢索特定產品的數量,然後使用 IronXL 在 Excel 庫存管理試算表中更新該數量。
IronOCR 是一種先進的OCR (光學字符識別) & 條碼讀取庫適用於 .NET 和 C#。 它允許開發者從圖像和 PDF 中讀取文字和條碼,該功能在 .NET 應用程式中特別有用。 當您需要從掃描文件或圖像中提取資料並在您的代碼中處理時,這會非常實用。
考慮一個使用 IronOCR 從掃描文件中提取學生身份證號的場景。 處理後,您將身份證號和相應的學生詳細資料存儲在 Dictionary 中。 在檢索特定學生的詳細資料時,可以使用 TryGetValue
有效地從 Dictionary 中獲取資料。
IronBarcode 是一個用於 .NET 的條碼讀取和寫入庫。使用 IronBarcode,開發人員可以生成和讀取各種條碼和 QR 碼格式。它是一個強大的工具,可以將數據編碼和解碼為緊湊的機器可讀格式。
在實際場景中,想像你在零售系統中使用條碼來存儲產品信息。每個條碼可以對應於存儲為 Dictionary 中一個鍵的唯一產品 ID。當掃描條碼時,你可以使用 TryGetValue
快速從 Dictionary 中獲取並顯示其相關的產品詳細信息。
正如我們探索了標準 C# 特性(例如 TryGetValue
方法)與 Iron 程式庫的功能結合,我們可以明顯看到這些工具可以顯著提升您的開發流程。無論您是操作 PDF、Excel 文檔、OCR,還是條碼, Iron Suite 提供符合您需求的解決方案。
更吸引人的是,這些產品中的每一個都提供一個 免費試用讓您免費探索和嘗試這些功能。如果您決定繼續使用這些庫,許可證的起價為每個產品 $749。然而,如果您對多個 Iron 庫感興趣,您可以購買完整的 Iron Suite,其價格僅相當於兩個單獨產品的價格。