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

后端 未结 11 1898
长情又很酷
长情又很酷 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条回答
  •  Happy的楠姐
    2020-12-24 00:48

    Ah, the problems of generic code. Consider this block via Reflector:

    private void Insert(TKey key, TValue value, bool add)
    {
        int freeList;
        if (key == null)
        {
            ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
        }
    

    There is no way to rewrite this code to say "Nullable nulls are allowed, but don't allow reference types to be null".

    Ok, so how ab out not allowing TKey to be a "bool?". Well again, there is nothing in the C# language that would allow you to say that.

提交回复
热议问题