为了说明,我们来看一个简单的控制台应用程序,并在其中创建两个枚举:汽车和动物:
public enum Cars { Honda = 0,Toyota = 1,Chevrolet = 2 } public enum Animals { Dog = 0,Cat = 1,Tiger = 2 }
并在主要方法中做到这一点:
public static void Main() { List<Cars> cars = new List<Cars>(); List<Animals> animals = new List<Animals>(); cars.Add(Cars.Chevrolet); cars.Add(Cars.Honda); cars.Add(Cars.Toyota); foreach (Animals isItACar in cars) { Console.WriteLine(isItACar.ToString()); } Console.ReadLine(); }
它将在控制台中打印:
06002
为什么会这样呢?我的第一个猜测是,枚举实际上并不是一个类型,它只是和int,但这不是真的:如果我们写:
Console.WriteLine(Animals.Tiger.GetType()全名.);
我们会得到他的完全合格的名字打印!那为什么这样呢?
解决方法
让我们重写一下你的循环:
public static void Main() { List<Cars> cars = new List<Cars>(); List<Animals> animals = new List<Animals>(); cars.Add(Cars.Chevrolet); cars.Add(Cars.Honda); cars.Add(Cars.Toyota); foreach (Cars value in cars) { // This time the cast is explicit. Animals isItACar = (Animals) value; Console.WriteLine(isItACar.ToString()); } Console.ReadLine(); }
现在这个结果让你感到惊讶吗?希望不是,除了可以从一个枚举到另一个枚举的事实.这只是您原始代码正在做的更为明确的版本.
事实上,每个foreach循环中都有一个隐式的转换(尽管通常是一个no-op)是大多数开发人员会发现混乱的一点,我认为.
从C#3.0规范的8.8.4节:
The above steps,if successful,
unambiguously produce a collection
type C,enumerator type E and element
type T. A foreach statement of the
form
foreach (V v in x) embedded-statement
is then expanded to:
{ E e = ((C)(x)).GetEnumerator(); try { V v; while (e.MoveNext()) { v = (V)(T)e.Current; embedded-statement } } finally { ... // Dispose e } }
枚举转换本身包含在6.2.2节中:
The explicit enumeration conversions
are:
>从sbyte,byte,short,ushort,int,uint,long,ulong,char,float,double或decimal到任何枚举类型.
>从任何枚举类型到sbyte,double或decimal.
>从任何枚举类型到任何其他枚举类型.
An explicit enumeration conversion between two types is processed by treating any participating enum-type as the underlying type of that enum-type,and then performing an implicit or explicit numeric conversion between the resulting types. For example,given an enum-type E with and underlying type of int,a conversion from E to byte is processed as an explicit numeric conversion (§6.2.1) from int to byte,and a conversion from byte to E is processed as an implicit numeric conversion (§6.1.2) from byte to int.