字典中的无效键

Sao*_*Ali 16 c# collections

为什么字典不仅仅null在使用无效密钥索引到集合时返回?

cdh*_*wie 27

因为通用字典可以包含值类型的实例,并且null对值类型无效.例如:

var dict = new Dictionary<string, DateTime>();
DateTime date = dict["foo"]; // What should happen here?  date cannot be null!
Run Code Online (Sandbox Code Playgroud)

您应该使用字典的TryGetValue方法:

var dict = new Dictionary<string, DateTime>();
DateTime date;

if (dict.TryGetValue("foo", out date)) {
    // Key was present; date is set to the value in the dictionary.
} else {
    // Key was not present; date is set to its default value.
}
Run Code Online (Sandbox Code Playgroud)

此外,存储引用类型的字典仍将存储空值.并且您的代码可能会将"value is null"视为与"key not exists"不同.


Bee*_*Guy 5

Microsoft 决定 =)
进行内联检查以避免这种情况。

object myvalue = dict.ContainsKey(mykey) ? dict[mykey] : null;
Run Code Online (Sandbox Code Playgroud)