Enum inheriting from int

前端 未结 9 1270
借酒劲吻你
借酒劲吻你 2020-12-17 08:43

I\'ve found this all over the place in this code:

public enum Blah: int
{
    blah = 0,
    blahblah = 1
}

Why would it need to inherit fro

9条回答
  •  庸人自扰
    2020-12-17 09:08

    You don't need to, it's implied. According to MSDN:

    An enumeration is a set of named constants whose underlying type is any integral type except Char. If no underlying type is explicitly declared, Int32 is used. Enum is the base class for all enumerations in the .NET Framework.

    This means you could usebyte, sbyte, ushort, int, uint, long, or ulong.

    Also, setting the values the way you have described (blah=0, blahblah=1), while redundant, is OK, since, according to the C# Specification

    If the declaration of the enum member has no initializer, its associated value is set implicitly, as follows:

    • If the enum member is the first enum member declared in the enum type, its associated value is zero.

    • Otherwise, the associated value of the enum member is obtained by increasing the associated value of the textually preceding enum member by one. This increased value must be within the range of values that can be represented by the underlying type, otherwise a compile-time error occurs.

提交回复
热议问题