为什么开关枚举接受隐式转换为0,但没有任何其他的整数? [英] Why switch for enum accepts implicit conversion to 0 but no for any other integer?

查看:210
本文介绍了为什么开关枚举接受隐式转换为0,但没有任何其他的整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个:

 枚举SomeEnum
{
    A = 0,
    B = 1,
    C = 2
}
 

现在的编译器可以让我写的:

  SomeEnum X = SomeEnum.A;
开关(X)
{
    情况下0://< ---考虑SomeEnum.A
        打破;
    案例SomeEnum.B:
        打破;
    案例SomeEnum.C:
        打破;
    默认:
        打破;
}
 

0 被认为是 SomeItems.A 。但是,我不能写:

  SomeEnum X = SomeEnum.A;
开关(X)
{
    情况下0:
        打破;
    案例1://< ---这是一个编译错误。
        打破;
    案例SomeEnum.C:
        打破;
    默认:
        打破;
}
 

为什么只有隐式转换存在 0

解决方案

从的 ECMA-334(C#语言规范)

  

13.1.3隐式枚举​​转换

     
    

这是隐式枚举转换允许小数整数字面     0被转换到任何enum-type

  

枚举的默认值是 0 键,在编译时就知道,这就是为什么它被允许在switch语句。对于值除 0 ,它不能在编译时确定该值是否存在于枚举与否。

枚举(C#参考)

  

分配额外值枚举的新版本,或改变   枚举成员在新版本值,可能会导致问题   相关源$ C ​​$ C。它往往是的情况下枚举值   在开关语句中使用,而且如果附加元素已被添加   以枚举类型,测试的默认值可以返回true   出乎意料的。

There is an:

enum SomeEnum
{
    A = 0,
    B = 1,
    C = 2
}

Now compiler allows me to write:

SomeEnum x = SomeEnum.A;
switch(x)
{
    case 0: // <--- Considered SomeEnum.A
        break;
    case SomeEnum.B:
        break;
    case SomeEnum.C:
        break;
    default:
        break;
}

0 is considered SomeItems.A. But I can't write:

SomeEnum x = SomeEnum.A;
switch(x)
{
    case 0:
        break;
    case 1: // <--- Here is a compilation error.
        break;
    case SomeEnum.C:
        break;
    default:
        break;
}

Why only implicit conversion exists for 0?

解决方案

From ECMA-334 (C# Language Specification)

13.1.3 Implicit enumeration conversions

An implicit enumeration conversion permits the decimal-integer-literal 0 to be converted to any enum-type.

enum's default value is 0 and at compile time it is known that is why it is allowed in the switch statement. For value other than 0, it can't be determine at compile time whether this value will exist in the enum or not.

enum (C# Reference)

Assigning additional values new versions of enums, or changing the values of the enum members in a new version, can cause problems for dependant source code. It is often the case that enum values are used in switch statements, and if additional elements have been added to the enum type, the test for default values can return true unexpectedly.

这篇关于为什么开关枚举接受隐式转换为0,但没有任何其他的整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆