c# – 枚举Int32类型的成员[复制]

Possible Duplicate:
07000

这可能是一个相当基本/简单的问题
我正在以下列方式创建一个枚举.

案例1编译完美.但案例2引发了错误.
我理解int和Int32在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
    }

这里的区别是什么,以及当enum的成员被指定为Int32类型时C#不编译代码的原因是什么?

a Microsoft bug report here开始:

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.

It is “by design”.

  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.

  2. 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.

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

  4. But, it allows you to use the keyword to control. The intent is to prevent your using names of any types that derive from System.ValueType when declaring other types. The original intent is to provide a tightly controlled mechanism that allows you to declare types that inherit from System.ValueType.
    However, MSDN says “The C# type keywords and their aliases are interchangeable”, which often let customers feel confused/inexplicable. They think it’s a compiler or grammar bug.

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).

https://stackoverflow.com/questions/3774650/enum-members-of-int32-type

转载注明原文:c# – 枚举Int32类型的成员[复制]