枚举作为字典键 [英] Enum as Dictionary keys
问题描述
假设拥有
enum SomeEnum { One, Two, Three };
SomeEnum是一个枚举,因此应该从Enum继承,所以为什么写:
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>();
编译器抱怨无法将SomeEnum隐式转换为Enum?
The compiler complains that it cannot implicitly convert SomeEnum to Enum?
推荐答案
我认为这是因为协方差。
简而言之:
aDictionary
将是 Dictionary< SomeEnum,SomeClass>
,但在当前上下文中它称为字典< Enum,SomeClass>
。
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>();
这篇关于枚举作为字典键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!