开发者

enum members of Int32 type [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

C# int, Int32 and enum's

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

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

Case 1

    [Flags]
    public enum MyEnum : int
    {
        Red = 0x1,
        Green = 0x2,
        Blue = 开发者_如何学C0x4
    }

Case 2

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

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?


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜