字典中的键无效
当使用无效键对集合进行索引时,为什么字典不只是返回 null?
Why do dictionaries not just return null
when an invalid key is used to index into the collection?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
因为泛型字典可以包含值类型的实例,而 null 对于值类型无效。例如:
您应该使用字典的 TryGetValue 方法:
此外,存储引用类型的字典仍将存储空值。并且您的代码可能会认为“值为空”与“键不存在”不同。
Because generic dictionaries could contain instances of a value type, and null is not valid for a value type. For example:
You should instead use the TryGetValue method of dictionary:
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."
微软决定 =)
进行内联检查以避免这种情况。
Microsoft decided that =)
Do an inline check to avoid that.
尝试使用
Dictionary.TryGetValue Method
或者也许
Dictionary.ContainsKey 方法
Try using
Dictionary.TryGetValue Method
or maybe
Dictionary.ContainsKey Method
实际原因:因为字典可以存储空值。在您的场景中,您将无法区分这种情况与异常。
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.
繁荣!
http://github.com/jsonmez/Defaultable-Dictionary
http://simpleprogrammer.com/2011/08/14/making-switch-refactorings-更好的默认字典/
Boom!
http://github.com/jsonmez/Defaultable-Dictionary
http://simpleprogrammer.com/2011/08/14/making-switch-refactorings-better-defaultable-dictionary/