C# - 需要一个IDictionary实现,将允许null键 [英] C# -- Need an IDictionary implementation that will allow a null key

查看:232
本文介绍了C# - 需要一个IDictionary实现,将允许null键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我想是这样的:

Basically, I want something like this:

Dictionary<object, string> dict = new Dictionary<object, string>();
dict.Add(null, "Nothing");
dict.Add(1, "One");



是否有任何内置到基础类库允许这样做?上面的代码将在运行时添加null键时抛出异常。

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.

感谢

推荐答案

您可以尽量避免使用空,并创建一个特殊的单值类,做同样的事情。例如:

You could avoid using null and create a special singleton value class that does the same thing. For example:

public sealed class Nothing
{ 
  public static readonly Nothing Value = new Nothing(); 
  private Nothing() {}
}

Dictionary<object, string> dict = new Dictionary<object, string>();
dict.add(Nothing.Value, "Nothing");
dict.add(1, "One");

这做法会,如果你打算让您的收藏更强类型无法正常工作您想关键是字符串。由于字符串是密封的,你不能继承它创建一个空的特殊价值的替代品。你的选择变得有点复杂。你可以:

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:


  1. 创建一些特别的恒定值来表示空/空的情况。一种哈克,绝对混乱的路径。这可能是一个可行的方法,如果字典是完全私人的一些实现类,你可以写一些编码/解码工具方法以避免传染的,你怎么所有的地方翻译键的知识。

  2. 创建自己的实现IDictionary中的在内部委托给一个解释<>实例 - 除了空的情况。这违反了IDictionary的<所记录的期望;>接口,不说null键应该抛出一个异常。但是,你可能能够逃脱它,如果它是为您解决实际问题的唯一途径。仅当您拥有和创建字典实例的工作。

  3. 找到一个方法来解决你的问题没有存储在字典中的空键。例如,考虑不填充在字典null键和有一些特殊情况下的逻辑来处理它。钥匙一定要哈希的,可比的底层实现,这就是为什么空通常禁止工作。

顺便说一句,不你的字典钥匙真正需要的关键是对象?这可能会导致因引用相等微妙的错误使用,你可能打算的equals()进行评估,作为比较的基础。

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.

这篇关于C# - 需要一个IDictionary实现,将允许null键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆