使用c# 9.0引入的条件访问运算符 ?.[] 可以安全读取可能为 null 的字典中的键。当字典对象本身为 null 时,该表达式会直接返回 null,从而避免抛出 nullreferenceexception;如果字典不为 null 但键不存在,则根据字典类型(如 dictionary)返回默认值或 null。

如何判断键是否存在并获取其值?
在确保字典不为 null 的前提下,应使用 TryGetValue 方法来判断键是否存在并获取值。这是比 ContainsKey 更高效的做法,因为它在一次查找中同时完成了存在性检查和值提取,避免了重复的哈希计算。

using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// 模拟一个可能为 null 的字典
Dictionary<string int> dict = null;
// 1. 安全读取:使用条件访问
int? value1 = dict?["key1"];
Console.WriteLine($"Safe read result: {value1}"); // Output: Safe read result:
// 假设字典已初始化
dict = new Dictionary<string int>
{
["key1"] = 10,
["key2"] = 20
};
// 2. 高效读取:使用 TryGetValue
if (dict.TryGetValue("key1", out int result))
{
Console.WriteLine($"Found key1 with value: {result}");
}
else
{
Console.WriteLine("Key not found or dictionary was null");
}
// 3. 处理不存在的键
if (dict.TryGetValue("nonexistent", out int missingResult))
{
Console.WriteLine(missingResult);
}
else
{
Console.WriteLine("Key 'nonexistent' does not exist.");
}
}
}
</string></string>
上述代码展示了两种主要场景。首先,当 dict 为 null 时,dict?["key1"] 返回 null,赋值给可空类型 int? 是安全的。其次,当字典有效时,TryGetValue 返回布尔值指示键是否存在,并通过 out 参数返回实际值。对于不存在的键,TryGetValue 返回 false,且输出参数被设为类型的默认值(对于 int 是 0),但通常我们只关心返回值是否为 true。
不同字典类型在键缺失时的行为差异是什么?
不同的字典实现类在键缺失时表现不同。标准的 Dictionary 在使用索引器 [] 访问不存在的键时会抛出 KeyNotFoundException,而 ConcurrentDictionary 的 GetOrAdd 或索引器行为则需特别注意。此外,Lookup 或自定义字典可能返回默认值。理解这些差异有助于选择正确的访问方式。

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
class Program
{
static void Main()
{
// 1. Standard Dictionary behavior
var stdDict = new Dictionary<string string>
{
["a"] = "apple"
};
try
{
string val = stdDict["b"]; // Throws KeyNotFoundException
Console.WriteLine(val);
}
catch (KeyNotFoundException)
{
Console.WriteLine("Standard Dictionary throws exception for missing key.");
}
// 2. ConcurrentDictionary behavior with GetOrAdd
var concDict = new ConcurrentDictionary<string string>
{
["a"] = "apple"
};
// GetOrAdd will add the key if it doesn't exist
string concVal = concDict.GetOrAdd("b", "banana");
Console.WriteLine($"ConcurrentDictionary GetOrAdd result: {concVal}"); // Output: banana
// 3. Using GetValueOrDefault (available in .NET Core 2.0+ / .NET 5+)
// This returns default(T) if key is not found, without throwing
string stdValOrDefault = stdDict.GetValueOrDefault("b");
Console.WriteLine($"GetValueOrDefault result: {(stdValOrDefault == null ? "null" : stdValOrDefault)}"); // Output: null
}
}
</string></string>
这段代码对比了三种情况。标准 Dictionary 在访问不存在的键时抛出异常,因此必须配合 TryGetValue 或 ContainsKey 使用。 ConcurrentDictionary 的 GetOrAdd 方法在键不存在时会添加新键并返回新值,这改变了字典状态,需谨慎使用。从 .NET Core 2.0 开始,Dictionary 提供了 GetValueOrDefault 方法,它不会抛出异常,而是返回值的类型默认值(对于引用类型是 null,对于值类型是 0 等),这使得它在某些场景下比 TryGetValue 更简洁,但需注意区分“键不存在”和“值为默认值”的情况。











