Enum as Dictionary keys

后端 未结 2 1278
情书的邮戳
情书的邮戳 2021-01-11 09:17

Suppose to have

enum SomeEnum { One, Two, Three };

SomeEnum is an enum so it is supposed to inherit from Enum so why if I write:

         


        
2条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-11 10:16

    I believe that's because of covariance.

    In short:

    aDictionary will be a Dictionary, but in the current context it is known as Dictionary.

    Had your declaration been allowed, the compiler should afterwards let you do:

    aDictionary.Add(someValueFromAnotherEnumUnrelatedToSomeEnum, aValue);
    

    which is obviously inconsistent with respect to the actual type of the dictionary.

    That's why co-variance is not allowed by default and you have to explicitly enable it in cases where it makes sense.

    The conclusion is that you have to specify the type exactly:

    Dictionary aDictionary = 
        new Dictionary();
    

提交回复
热议问题