C# 字典中查找特定 Key 并获取值:ContainsKey 和 [] 操作符
你可以使用 'ContainsKey' 方法来判断字典中是否包含指定的 key,并且使用 '[]' 操作符来获取 key 对应的值。以下是一个示例代码:
Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add("layer1", "value1");
dict.Add("layer2", "value2");
if (dict.ContainsKey("layer"))
{
string value = dict["layer"];
Console.WriteLine(value);
}
else
{
Console.WriteLine("Key 'layer' does not exist in the dictionary.");
}
在上面的示例中,我们首先判断字典中是否包含 'layer' 这个 key,如果存在则使用 '[]' 操作符取出对应的值并打印输出;如果不存在,则打印输出提示信息。
原文地址: https://www.cveoy.top/t/topic/pi9T 著作权归作者所有。请勿转载和采集!