Cly*_*yde 13 c# collections idictionary
基本上,我想要这样的东西:
Dictionary<object, string> dict = new Dictionary<object, string>();
dict.Add(null, "Nothing");
dict.Add(1, "One");
Run Code Online (Sandbox Code Playgroud)
是否有任何内置到基类库中允许这样做?添加null键时,前面的代码将在运行时抛出异常.
谢谢
LBu*_*kin 11
您可以避免使用null并创建一个执行相同操作的特殊单例值类.例如:
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");
Run Code Online (Sandbox Code Playgroud)
如果您打算使您的集合更强类型,这种方法将无法工作 - 例如,您希望密钥是一个字符串.由于字符串是密封的,因此您无法继承它以创建"特殊值"替代null.你的选择变得有点复杂.你可以:
顺便说一句,你的词典密钥真的需要密钥object吗?这可能会导致细微的错误,因为您可能希望将Equals()作为比较的基础进行评估.
这个怎么样?
public class NullableDictionnary<T1, T2> : Dictionary<T1, T2>
{
T2 null_value;
public T2 this[T1 key]
{
get
{
if (key == null)
{ return null_value; }
return base[key];
}
set
{
if (key == null)
{ null_value = value; }
else
{ base[key] = value; }
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9840 次 |
| 最近记录: |