Why can't you use null as a key for a Dictionary?

后端 未结 11 1902
长情又很酷
长情又很酷 2020-12-24 00:33

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

This code:

var nullableBoolLabels = new System.Collect         


        
11条回答
  •  天命终不由人
    2020-12-24 00:50

    You can't use a null bool? because nullable types are meant to act like reference types. You can't use a null reference as a dictionary key, either.

    The reason you can't use a null reference as a dictionary key probably comes down to a design decision at Microsoft. Allowing null keys requires checking for them, which makes the implementation slower and more complicated. For example, the implementation would have to avoid using .Equals or .GetHashCode on a null reference.

    I agree that allowing null keys would be preferable, but it's too late to change the behavior now. If you need a workaround you can write your own dictionary with allowed null keys, or you could write a wrapper struct which implicitly converts to/from T and make that the key-type for your dictionary (ie. the struct would wrap the null and handle comparing and hashing, so the dictionary never 'sees' the null).

提交回复
热议问题