【发布时间】:2010-12-17 06:55:27
【问题描述】:
当使用无效键索引集合时,为什么字典不只返回 null?
【问题讨论】:
标签: c# collections
当使用无效键索引集合时,为什么字典不只返回 null?
【问题讨论】:
标签: c# collections
微软决定 =)
进行内联检查以避免这种情况。
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!
您应该改用字典的 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.
}
此外,存储引用类型的字典仍将存储空值。您的代码可能会认为“值为空”与“键不存在”不同。
【讨论】:
default(DateTime) 而不是 null。
default(DateTime),那么您无法区分“值是default(DateTime)”和“键不存在”,至少无需额外调用ContainsKey()(这将不必要地手术成本翻倍)。对于包含引用类型作为值的字典,除了“键不存在”之外,null 可能是一个有意义的状态。
实际原因:因为字典可以存储空值。在您的场景中,您将无法区分这种情况,但有例外。
【讨论】:
【讨论】: