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

Possible Duplicate:




    public enum MyEnum : int
        Red = 0x1,
        Green = 0x2,
        Blue = 0x4


    public enum MyEnum : Int32
        Red = 0x1,
        Green = 0x2,
        Blue = 0x4


a Microsoft bug report here开始:

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

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