C# 字典中的键无效

C# 字典中的键无效,c#,collections,C#,Collections,当一个无效的键被用于索引到集合中时,为什么字典不只是返回null呢?微软决定=) 进行内联检查以避免这种情况 object myvalue = dict.ContainsKey(mykey) ? dict[mykey] : null; 试用 或许 因为泛型词典可能包含值类型的实例,而null对于值类型无效。例如: var dict = new Dictionary<string, DateTime>(); DateTime date = dict["foo"]; // What

当一个无效的键被用于索引到集合中时,为什么字典不只是返回null呢?

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

object myvalue = dict.ContainsKey(mykey) ? dict[mykey] : null;
试用

或许


因为泛型词典可能包含值类型的实例,而null对于值类型无效。例如:

var dict = new Dictionary<string, DateTime>();
DateTime date = dict["foo"]; // What should happen here?  date cannot be null!
var dict=newdictionary();
DateTime date=dict[“foo”];//这里会发生什么?日期不能为空!
您应该改为使用dictionary的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.
}
var dict=newdictionary();
日期时间日期;
if(dict.TryGetValue(“foo”,过期)){
//键存在;日期设置为字典中的值。
}否则{
//键不存在;日期设置为其默认值。
}

此外,存储引用类型的字典仍将存储空值。您的代码可能会考虑“值为null”不同于“KEY不存在”。

实用原因:因为字典可以存储一个空值。在您的场景中,您将无法区分这种情况和例外情况。


这并不能真正说明设计决策的原因;他们可以很容易地让它返回
default(DateTime)
,而不是null。@Extragorey是的,尤其是最后一句话:无论“not found”值是什么,您可能需要将该值存储为有意义的值。如果获取未找到的密钥返回
default(DateTime)
,则您无法区分“value is
default(DateTime)
”和“key is not present”,至少不需要额外调用
ContainsKey()
(这将不必要地增加操作成本)。对于包含引用类型作为值的字典,除了“key is not present”之外,
null
可能是一种有意义的状态。谢谢,这种解释更有意义。