在C#中,通过key取值可以使用Dictionary的TryGetValue方法或者直接使用[key]索引操作符。 使用TryGe
在C#中,通过key取值可以使用Dictionary的TryGetValue方法或者直接使用[key]索引操作符。
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);
}
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方法来避免异常的发生。
--结束END--
本文标题: c#字典怎么通过key取值
本文链接: https://www.lsjlt.com/news/579225.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0