gpt4 book ai didi

c# - 使用字典时如何避免运行时错误

转载 作者:太空宇宙 更新时间:2023-11-03 21:45:14 25 4
gpt4 key购买 nike

我有一段代码表示字典和搜索键数组。

Dictionary<string, string> items = new Dictionary<string, string>()
{
{"1","Blue"},
{"2","Green"},
{"3","White"}
};

string[] keys = new[] { "1", "2", "3", "4" };

当我传递字典中不存在的键时,如何安全地避免运行时错误?

最佳答案

How to safely avoid the run time error when i pass a key that is not present in dictionary?

您还没有展示您目前是如何尝试这样做的,但是您可以使用 Dictionary<,>.TryGetValue :

foreach (string candidate in keys)
{
string value;
if (items.TryGetValue(candidate, out value))
{
Console.WriteLine("Key {0} had value {1}", candidate, value);
}
else
{
Console.WriteLine("No value for key {0}", candidate);
}
}

关于c# - 使用字典时如何避免运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17382694/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com