新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

c#字典获取值的有哪些方法,c# 字典取值

发布时间:2024-05-15 18:46:18

c#字典获得值的有哪些方法

要获得字典中的值,可使用字典的索引器(Indexer)还是TryGetValue方法。

  1. 使用索引器:
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异常
  1. 使用TryGetValue方法:
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方法更安全,不会抛出异常,合适用于判断字典中是否是包括指定的键。