需要 IDictionary允许空键的实现
基本上,我想要这样的东西:
Dictionary<object, string> dict = new Dictionary<object, string>();
dict.Add(null, "Nothing");
dict.Add(1, "One");
基类库中是否有任何内置的允许这样做?上面的代码在添加 null 键时会在运行时抛出异常。
Basically, I want something like this:
Dictionary<object, string> dict = new Dictionary<object, string>();
dict.Add(null, "Nothing");
dict.Add(1, "One");
Are there any built into the base class library that allow this? The preceding code will throw an exception at runtime when adding the null key.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
您可以避免使用 null 并创建一个特殊的单例值类来执行相同的操作。例如:
如果您打算使集合具有更强的类型,则此方法将无法工作 - 比方说您希望键是字符串。由于字符串是密封的,因此您无法继承它来创建空值的“特殊值”替代品。您的选择会变得更加复杂。您可以:
顺便说一句,你的字典键真的需要键是
object
吗?由于在您可能希望将 Equals() 作为比较基础进行评估的情况下使用引用相等,这可能会导致微妙的错误。You could avoid using null and create a special singleton value class that does the same thing. For example:
This approach will fail to work if you intend to make your collection more strongly typed - let's say for example you want the key to be a string. Since string is sealed you can't inherit from it to create a "special value" substitute for null. Your alternatives become a bit more complicated. You could:
As an aside, does your dictionary key really need the key to be
object
? This can lead to subtle bugs due to reference equality being used where you may have intended Equals() to be evaluated as the basis for comparison.这个怎么样?
How about this?
NameValueCollection 可以采用 null 键,但它不实现 IDictionary。然而,从 DictionaryBase 派生并提供添加/删除/索引器等将非常容易,只需用内置的内容替换 null 即可:
NameValueCollection can take a null key but it does not implement IDictionary. It would however be pretty easy to derive from DictionaryBase and provide Add/Remove/Indexers etc that simply replace null with something built in like:
您可以简单地使用 ValueTuple 作为 key 的包装器,例如:
You can simply use ValueTuple as a wrapper for key, for example:
不需要不同的字典实现。
看看我在这里的回答:
https://stackoverflow.com/a/22261282/212272
您还可以保持字典强类型化:
No need for a different implementation of Dictionary.
Take a look at my answer here:
https://stackoverflow.com/a/22261282/212272
You will also be able to keep your dictionary strongly typed:
如果键是枚举,您可以使用不存在的值而不是 null,如
(YourEnum)(-1)
If key is enum, you can use not existing value instead of null like
(YourEnum)(-1)
key 真的需要为 NULL 吗?集合中的键是一个索引。对我来说,集合中的索引为 NULL 没有多大意义。
也许创建一个新类
Does the key literally need to be NULL? The key in the collection works out to be an index. It doesn't make a lot of sense to me to have NULL for an index in a collection.
Maybe create a new class
jestro 的答案略有不同,以提供更清晰的(对我来说)解决方案,使其更明确您想要做什么。显然,这可以根据需要进行扩展。但你明白了,只需制作一个包装纸即可。
A slight variation on jestro's answer to make for a cleaner(to me) solution that makes it more explicit what you are trying to do. Obviously this could be extended as needed. But you get the picture, just make a wrapper.