在c#中访问多层字典时,直接通过索引器(如 dict["a"]["b"])访问不存在的中间键会抛出 keynotfoundexception。要避免异常,最稳妥的做法是在访问前使用 containskey 或 trygetvalue 逐层检查键的存在性,或者使用 c# 8.0 引入的空值传播运算符 ?. 进行安全导航。

如何安全地逐层检查嵌套字典的键?
可以通过链式调用 ContainsKey 来确保每一层键都存在。如果任何一层缺失,立即返回默认值或处理逻辑,从而避免抛出异常。

using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var dict = new Dictionary<string, Dictionary<string, int>>
{
{ "user1", new Dictionary<string, int> { { "score", 100 } } }
};
string outerKey = "user2";
string innerKey = "score";
int defaultValue = -1;
// 安全访问逻辑
if (dict.ContainsKey(outerKey))
{
var innerDict = dict[outerKey];
if (innerDict.ContainsKey(innerKey))
{
Console.WriteLine(innerDict[innerKey]);
}
else
{
Console.WriteLine($"Inner key '{innerKey}' not found.");
}
}
else
{
Console.WriteLine($"Outer key '{outerKey}' not found.");
}
}
}
预期输出:Outer key 'user2' not found.
如何使用 TryGetValue 优化多层字典的查找性能?
TryGetValue 比 ContainsKey 更高效,因为它在一次哈希查找中同时完成存在性检查和值获取。在多层结构中,可以连续使用 TryGetValue 来避免重复查找。

using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var dict = new Dictionary<string, Dictionary<string, int>>
{
{ "user1", new Dictionary<string, int> { { "score", 100 } } }
};
string outerKey = "user1";
string innerKey = "score";
int result;
// 使用 TryGetValue 优化
if (dict.TryGetValue(outerKey, out var innerDict) &&
innerDict.TryGetValue(innerKey, out result))
{
Console.WriteLine(result);
}
else
{
Console.WriteLine("Access failed or key missing.");
}
}
}
预期输出:100
当使用空值传播运算符 ? 访问深层键时,结果类型是什么?
使用 ? 运算符(如 dict["a"]?["b"])时,如果中间层为 null 或键不存在,整个表达式将返回 null。对于值类型(如 int),结果将是可空类型 int?,需要进一步解包或提供默认值。


















