Linux 拨号vps windows公众号手机端

c#字典怎么通过key取值

lewis 9年前 (2016-11-21) 阅读数 12 #程序编程
文章标签 c#

在C#中,通过key取值可以使用Dictionary的TryGetValue方法或者直接使用[key]索引操作符。

  1. 使用TryGetValue方法:
Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("key1", 100);
dict.Add("key2", 200);

int value;
if (dict.TryGetValue("key1", out value))
{
    Console.WriteLine("Value for key1: " + value);
}
  1. 使用[key]索引操作符:
Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("key1", 100);
dict.Add("key2", 200);

int value = dict["key1"];
Console.WriteLine("Value for key1: " + value);

注意:在使用[key]索引操作符时,如果指定的key不存在于字典中,会抛出KeyNotFoundException异常。因此最好使用TryGetValue方法来避免异常的发生。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门