字典是C#中常用的數據結構之一,它提供了鍵值對存儲數據的方式。當我們需要獲取字典中某個鍵對應的值時,TryGetValue方法是一個不錯的選擇。本文將詳細闡述如何使用TryGetValue方法在C#中獲取字典中的值,並從以下幾個方面進行講解:
一、什麼是TryGetValue方法
TryGetValue是一個字典類型(Dictionary)的擴展方法,它用於獲取與指定的鍵相關聯的值,並返回一個表示是否檢索成功的值。如果檢索成功,則返回true和相關聯的值;否則返回false。
舉個例子,在以下Dictionary中,我們可以通過TryGetValue方法獲取與”key1″相關聯的值:
Dictionary<string, int> dict = new Dictionary<string, int>(); dict.Add("key1", 1); dict.Add("key2", 2); int value; bool exist = dict.TryGetValue("key1", out value); if (exist) { Console.WriteLine("The value of key1 is {0}", value); } else { Console.WriteLine("The key1 is not exist in the dictionary"); }
執行結果會輸出:The value of key1 is 1。
二、TryGetValue方法的作用
TryGetValue方法主要用於以下兩種情況:
1、避免異常
在我們需要獲取字典中某個鍵對應的值時,如果直接使用字典的indexer獲取值,當鍵不存在時,會拋出KeyNotFoundException異常,為了避免這種異常的發生,TryGetValue方法成為了一個不錯的選擇。
舉個例子,在以下Dictionary中,我們嘗試直接獲取一個不存在的鍵的值,程序會拋出異常。
Dictionary<string, int> dict = new Dictionary<string, int>(); dict.Add("key1", 1); dict.Add("key2", 2); int value = dict["key3"];
執行結果會輸出:System.Collections.Generic.KeyNotFoundException: ‘The given key was not present in the dictionary.’
但是,如果我們使用TryGetValue方法嘗試獲取一個不存在的鍵的值,程序會返回false,並不會拋出異常。
Dictionary<string, int> dict = new Dictionary<string, int>(); dict.Add("key1", 1); dict.Add("key2", 2); int value; bool exist = dict.TryGetValue("key3", out value); if (exist) { Console.WriteLine("The value of key3 is {0}", value); } else { Console.WriteLine("The key3 is not exist in the dictionary"); }
執行結果會輸出:The key3 is not exist in the dictionary
2、提高效率
將TryGetValue方法與containsKey方法結合使用,可以進一步提高程序的效率。
containsKey方法用於檢測字典中是否包含指定的鍵,如果包含則返回true,否則返回false。我們可以先使用containsKey方法判斷鍵是否存在,再使用TryGetValue方法獲取鍵對應的值。
舉個例子,在以下Dictionary中,我們使用containsKey方法以及TryGetValue方法獲取某個鍵對應的值。
Dictionary<string, int> dict = new Dictionary<string, int>(); dict.Add("key1", 1); dict.Add("key2", 2); if (dict.ContainsKey("key1")) { int value; bool exist = dict.TryGetValue("key1", out value); if (exist) { Console.WriteLine("The value of key1 is {0}", value); } }
執行結果會輸出:The value of key1 is 1
三、小結
TryGetValue方法是C#中常用的獲取字典中某個鍵對應的值的方法,它能夠避免發生KeyNotFoundException異常,提高程序的效率。在實際開發中,我們可以根據具體情況來選擇使用。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/185596.html