【问题标题】:Default Enum type, why this code does not compile? [duplicate]默认枚举类型,为什么这段代码不编译? [复制]
【发布时间】:2013-11-19 15:32:03
【问题描述】:

我定义了一个枚举。我也有两种方法:

  1. 方法 1 - 将获取枚举类型 - 枚举默认类型为 int,因此它将打印 System.Int32

  2. 方法 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,这显然是一个存根。有些人喜欢经常使用大括号,这样他们就不必担心变量声明的冲突。

标签: c# enums


【解决方案1】:

您的代码必须是:

switch( color )
{
    case Color.RED:
        break;
...
}

switch ( (int)color)
{
    case 0:
        break;
...
}

【讨论】:

  • RED 枚举类型Color 的某个常量?
  • 应该是case Color.RED:
  • 是的,愚蠢的错误。感谢您指出这一点。
  • 问题是如果类型已经是 int,为什么我需要做大小写
  • @Yanshof enum 不是int,如果您指定的话,它只是基于 int 甚至字节。
【解决方案2】:

您可以直接通过Enum Types查看

试试这个:

          private void foo()
           {
            switch( color )
            {
                case Color.RED:
                {

                }
                break;

                case Color.GREEN:
                {

                }
                break;

                case Color.BLUE:
                {

                }
                break;
            }
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-11
    • 1970-01-01
    • 2012-07-06
    • 2013-08-08
    • 1970-01-01
    • 2019-11-28
    相关资源
    最近更新 更多