字典中的键无效

发布于 2024-10-07 17:31:41 字数 38 浏览 2 评论 0原文

当使用无效键对集合进行索引时,为什么字典不只是返回 null?

Why do dictionaries not just return null when an invalid key is used to index into the collection?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

断桥再见 2024-10-14 17:31:41

因为泛型字典可以包含值类型的实例,而 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.
}

此外,存储引用类型的字典仍将存储空值。并且您的代码可能会认为“值为空”与“键不存在”不同。

Because generic dictionaries could contain instances of a value type, and null is not valid for a value type. For example:

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

You should instead use the TryGetValue method of dictionary:

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.
}

Also, a dictionary that stores reference types will still store null values. And your code might consider "value is null" to be different from "key does not exist."

℡Ms空城旧梦 2024-10-14 17:31:41

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

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

Microsoft decided that =)
Do an inline check to avoid that.

object myvalue = dict.ContainsKey(mykey) ? dict[mykey] : null;
时常饿 2024-10-14 17:31:41

实际原因:因为字典可以存储空值。在您的场景中,您将无法区分这种情况与异常。

Practical reason: Because a Dictionary could store a null value. You wouldn't be able to differentiate this case with an exception, in your scenario.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文