为什么你不能用null作为一个关键的字典&LT

为什么你不能用null作为一个关键的字典&LT

本文介绍了为什么你不能用null作为一个关键的字典<布尔?字符串>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

显然,你不能使用的关键,即使你的关键是可空类型。

这code:

  VAR nullableBoolLabels =新System.Collections.Generic.Dictionary<布尔?字符串>
{
    {真,是},
    {假,否},
    {空,(N / A)}
};
 

......结果这个异常:

为什么会在.NET框架允许可空类型的一个关键,但不允许空值?

解决方案

它会告诉你同样的事情,如果你有一个词典< SOMETYPE,串> SOMETYPE 是一个引用类型,而你试图通过为重点,它不是只影响可空类型如布尔?。你可以使用任何类型的键,可为空或不是。

这一切都归结为一个事实,即你不能真正比较零点。我想后面不能够把逻辑的关键,那就是设计用来与其他对象进行比较的特性是,它使得它语无伦次比较引用。

如果你想从规格有原因的,它归结为一个一键不能为空引用的。

如果你想要一个可能的解决方法的为例,你可以尝试类似的东西Need一个IDictionary实现,将允许null键

Apparently, you cannot use a null for a key, even if your key is a nullable type.

This code:

var nullableBoolLabels = new System.Collections.Generic.Dictionary<bool?, string>
{
    { true, "Yes" },
    { false, "No" },
    { null, "(n/a)" }
};

...results in this exception:

Why would the .NET framework allow a nullable type for a key, but not allow a null value?

解决方案

It would tell you the same thing if you had a Dictionary<SomeType, string>, SomeType being a reference type, and you tried to pass null as the key, it is not something affecting only nullable type like bool?. You can use any type as the key, nullable or not.

It all comes down to the fact that you can't really compare nulls. I assume the logic behind not being able to put null in the key, a property that is designed to be compared with other objects is that it makes it incoherent to compare null references.

If you want a reason from the specs, it boils down to a "A key cannot be a null reference " on MSDN.

If you want an exemple of a possible workaround, you can try something similar to Need an IDictionary implementation that will allow a null key

这篇关于为什么你不能用null作为一个关键的字典&LT;布尔?字符串&GT;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 10:46