为什么你不能用null作为一个关键的字典<布尔?字符串>?你不、布尔、作为一个、能用

2023-09-03 09:52:41 作者:劳资的心禁止访问

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

这code:

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

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

  

值不能为空。   参数名:键

     

说明:当前Web请求的执行过程中发生未处理的异常。请检查堆栈跟踪有关该错误的详细信息以及它起源于code。

     

[ArgumentNullException:值不能为空。参数名:键]       System.ThrowHelper.ThrowArgumentNullException(ExceptionArgument参数)+44       System.Collections.Generic.Dictionary'2.Insert(TKEY的关键,TValue值,布尔加)+ 40       System.Collections.Generic.Dictionary'2.Add(TKEY的关键,TValue值)+13

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

解决方案

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

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

从一个案例说明MySQL源码的重要性

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

如果你想要一个可能的解决方法的为例,你可以尝试类似的东西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:

Value cannot be null. Parameter name: key

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

[ArgumentNullException: Value cannot be null. Parameter name: key] System.ThrowHelper.ThrowArgumentNullException(ExceptionArgument argument) +44 System.Collections.Generic.Dictionary'2.Insert(TKey key, TValue value, Boolean add) +40 System.Collections.Generic.Dictionary'2.Add(TKey key, TValue value) +13

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

 
精彩推荐