【发布时间】:2018-07-12 13:46:26
【问题描述】:
我们已经知道我们可以convert an enum to another type of enum,所以以下编译:
public class EnumTest
{
enum Enum1 { Foo };
enum Enum2 { Foo };
void Test ()
{
System.Enum e = new Enum2(); // compiles
Enum1 e1 = (Enum1)new Enum2(); // compiles with an explicit cast
}
}
但这不能编译:
public class EnumTest
{
enum Enum1 { Foo };
enum Enum2 { Foo };
void Test ()
{
List<System.Enum> eList = new List<Enum2>(); // doesn't compile
List<Enum1> e1List = (List<Enum1>)new List<Enum2>(); // doesn't compile
}
}
这是covariance 的问题吗?如果没有,有没有办法让它工作?
【问题讨论】:
-
您是否期望
Enum1,Foo始终等同于Enum2.Foo?如果Enum1.Foo等于整数 1 而Enum2.Foo等于整数 2 会怎样?
标签: c# collections enums