字典是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/n/185596.html