的Int32类型的枚举成员 [英] enum members of Int32 type

查看:104
本文介绍了的Int32类型的枚举成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
C#INT,的Int32和枚举的

这可能是一个而基本/简单的问题
我创建以下列方式枚举。

It could be a rather basic / simpler question I am creating an enum in the following way.

第1种情况不完全编译。但是案例2抛出一个错误。
我的理解int和的Int32意味着C#一样的。

Case 1 does compile perfectly. But Case 2 throws an error. To my understanding int and Int32 mean the same in C#.

案例1

    [Flags]
    public enum MyEnum : int
    {
        Red = 0x1,
        Green = 0x2,
        Blue = 0x4
    }

案例2

    [Flags]
    public enum MyEnum : Int32
    {
        Red = 0x1,
        Green = 0x2,
        Blue = 0x4
    }

为什么C#不编译代码指定了枚举的成员时,这里有什么区别是的Int32类型的?

What's the difference here and why C# doesn't compile the code when the enum's members are specified to be of Int32 type?

推荐答案

从的微软漏洞在这里报告

症状结果
。如果您使用System.Int16 /的Int32 / Int64的,而不是短/ INT /长宣布枚举,它会得到编译错误。

Symptom
If you use System.Int16/Int32/Int64 instead of Short/Int/Long to declare Enum, it will get compilation error.

根源结果
它是由设计。使用值类型别名正是需要枚举声明。

Root Cause
It's by design. Using value type alias is required exactly in Enum declaration.

这就是设计。


  1. 的语法是正确的。 C#规范明确规定,枚举的基础类型必须是字节,为sbyte,短,USHORT,INT,UINT,或长或ulong的。

  1. The syntax is correct. C# specification explicitly states that the enum's underlying type must be byte, sbyte, short, ushort, int, uint, long or ulong.

虽然基本型短和System.Int16都是同一个,他们并不像你认为是相同的。该System.Int16是一个类型,短则一个类型关键字。

Although the underlying type of "Short" and "System.Int16" are one and the same, they are not as identical as you assume. The System.Int16 is a type, and the Short is a type keyword.

值类型是密封的。不能从从System.ValueType派生的任何类继承。

ValueType is sealed. You cannot inherit from any class that derives from System.ValueType.

业务影响/客户体验结果
由于短和System.Int16的是同一个基本类型,可以互换,很多客户感到困惑/莫名其妙,为什么不能在枚举声明互换。他们认为这是一个编译器或语法错误。
客户的声音:
这听起来像一个小的编译器缺陷(小监守它很容易要解决)。
这里是MSDN说的话C#的关键字类型及其别名是可以互换的。
在我看来,这是一个真实的,但微小的编译器(或者语法)错误。
编译器可让您使用短这里不是事实System.Int16是编译器的怪癖(也许不是一个错误,而是一个怪癖)。

Business Impact / Customer Experience
Since the "Short" and "System.Int16" are the same one underlying type and can be interchangeable, many customers feel confused/inexplicable why it cannot be interchangeable in Enum declaration. They think it’s a compiler or grammar bug. The Voice of customers: This sounds like a small compiler bug (small becuase its easy to workaround). Here is what MSDN says "The C# type keywords and their aliases are interchangeable." In my view this is a real but tiny, compiler (or perhaps grammar) bug. The fact that the compiler lets you use "short" here and not "System.Int16" is a quirk of the compiler (perhaps not a bug, but a quirk).

这篇关于的Int32类型的枚举成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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