【发布时间】:2013-11-19 15:32:03
【问题描述】:
我定义了一个枚举。我也有两种方法:
方法 1 - 将获取枚举类型 - 枚举默认类型为 int,因此它将打印
System.Int32方法 2 - 将具有将枚举类型与简单数字进行比较的开关盒 - 因此,如果枚举是 int,则开关盒需要编译时没有问题且不进行任何转换。
但是这段代码没有编译,我得到了两个错误(案例 1 上的错误点和 switch 案例中的案例 2)
无法将类型“int”隐式转换为“Color”。存在显式转换(您是否缺少演员表?)
即使Color 类型是int,有人可以解释为什么我会收到错误?
要编译此代码,我需要将Color 转换为int。
代码:
public enum Color
{
RED, // 0
BLUE, // 1
GREEN // 2
};
Color color = Color.BLUE;
private void boo(object sender, EventArgs e)
{
string str = Enum.GetUnderlyingType( color.GetType() ).ToString();
// it will print 'System.Int32'
System.Console.WriteLine(str);
}
// the switch case make the compile error - but the color is int
private void foo()
{
switch( color )
{
case 0:
{
}
break;
case 1:
{
}
break;
case 2:
{
}
break;
}
}
【问题讨论】:
-
您的案例块不需要大括号
-
颜色是不是
int。它是Color,基础类型为int。为什么你认为枚举和整数完全一样? -
switch( (int)color ) 如果你不喜欢在 switch 中使用枚举值
-
你为什么不用 case RED: etc??
-
@Kevin,这显然是一个存根。有些人喜欢经常使用大括号,这样他们就不必担心变量声明的冲突。