C# 枚举作为字典键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18716734/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Enum as Dictionary keys
提问by sblandin
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:
SomeEnum 是一个枚举,所以它应该从 Enum 继承,所以为什么我写:
Dictionary<Enum, SomeClass> aDictionary = new Dictionary<SomeEnum, SomeClass>();
The compiler complains that it cannot implicitly convert SomeEnum to Enum?
编译器抱怨它不能将 SomeEnum 隐式转换为 Enum?
采纳答案by Cristian Lupascu
I believe that's because of covariance.
我相信这是因为covariance。
In short:
简而言之:
aDictionary
will be a Dictionary<SomeEnum, SomeClass>
, but in the current context it is known as Dictionary<Enum, SomeClass>
.
aDictionary
将是 a Dictionary<SomeEnum, SomeClass>
,但在当前上下文中它被称为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>();
回答by Krishna Sarma
Enum in its declaration is not a class that is equal to SomeEnum. It should be
其声明中的 Enum 不是一个等于 SomeEnum 的类。它应该是
Dictionary<SomeEnum, SomeClass> aDictionary = new Dictionary<SomeEnum, SomeClass>();