12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
ADADADADAD
编程知识 时间:2024-12-05 09:49:54
作者:文/会员上传
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
要获取字典中的值,可以使用字典的索引器(Indexer)或者TryGetValue方法。使用索引器:Dictionary<string, int> dict = new Dictionary<string, int>();dict.Add("apple", 10);dic
以下为本文的正文内容,内容仅供参考!本站为公益性网站,复制本文以及下载DOC文档全部免费。
要获取字典中的值,可以使用字典的索引器(Indexer)或者TryGetValue方法。
Dictionary<string, int> dict = new Dictionary<string, int>();dict.Add("apple", 10);dict.Add("orange", 5);int value = dict["apple"];Console.WriteLine(value); // 输出:10// 如果字典中不存在指定的键,则会抛出KeyNotFoundException异常
Dictionary<string, int> dict = new Dictionary<string, int>();dict.Add("apple", 10);dict.Add("orange", 5);int value;if (dict.TryGetValue("apple", out value)){Console.WriteLine(value); // 输出:10}else{Console.WriteLine("Key not found");}// TryGetValue方法不会抛出异常,如果字典中不存在指定的键,则返回false
使用索引器直接获取值更简洁,但可能会抛出异常;而TryGetValue方法更安全,不会抛出异常,适合用于判断字典中是否包含指定的键。
11-20
11-19
11-20
11-20
11-20
11-19
11-20
11-20
11-19
11-20
11-19
11-19
11-19
11-19
11-19
11-19