Enum as Dictionary keys

2019-02-16 08:22发布

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:

Dictionary<Enum, SomeClass> aDictionary = new Dictionary<SomeEnum, SomeClass>();

The compiler complains that it cannot implicitly convert SomeEnum to Enum?

标签: c# .net-2.0
2条回答
相关推荐>>
2楼-- · 2019-02-16 09:01

Enum in its declaration is not a class that is equal to SomeEnum. It should be

Dictionary<SomeEnum, SomeClass> aDictionary = new Dictionary<SomeEnum, SomeClass>();
查看更多
该账号已被封号
3楼-- · 2019-02-16 09:04

I believe that's because of covariance.

In short:

aDictionary will be a Dictionary<SomeEnum, SomeClass>, but in the current context it is known as Dictionary<Enum, SomeClass>.

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<SomeEnum, SomeClass> aDictionary = 
    new Dictionary<SomeEnum, SomeClass>();
查看更多
登录 后发表回答