是什么导致了枚举的这种奇怪行为?

What causes this strange behaviour of an enum?

在摆弄枚举时,我发现我的一个枚举有一个奇怪的行为。

考虑以下代码:

static void Main()
    {

        Console.WriteLine("Values");
        Console.WriteLine();
        foreach (Month m in Enum.GetValues(typeof(Month)))
        {
            Console.WriteLine(m.ToString());
        }
        Console.WriteLine();
        Console.WriteLine("Names");
        Console.WriteLine();
        foreach (var m in Enum.GetNames(typeof(Month)))
        {
            Console.WriteLine(m);
        }
        Console.ReadLine();
    }
    public enum Month
    {
        January,
        May,
        March,
        April
    }

此代码产生以下输出(如预期):

Values

January
May
March
April

Names

January
May
March
April

现在,假设我稍微更改了枚举,如下所示:

public enum Month
    {
        January = 3,
        May,
        March,
        April
    }

如果我运行相同的代码,将出现相同的结果(这很奇怪)。现在,如果我像这样更改我的枚举:

public enum Month
    {
        January = "g",
        May,
        March,
        April
    }

我收到以下编译器错误:

Cannot implicitly convert type 'string' to 'int'.

为什么编译器允许我将枚举值之一设置为 3,而不是 g?为什么第一个结果和第二个完全一样?如果我更改了 January 的值,那么为什么 GetValues 不打印 3?

因为枚举只有certain approved types个,int就是其中之一。

默认情况下,枚举由 int 支持。它们只是附加到各种 int 值的标签。您可以让编译器选择将每个枚举值映射到哪些整数,也可以显式地进行。

除了 int(例如 bytelong)之外,您还可以创建由其他数字类型支持的枚举。

语法如下所示:

public enum Month : long
{
    January = 50000000000, //note, too big for an int32
    May,
    March,
    April
}

您不能拥有由非数字类型支持的枚举,例如 string

这就是枚举在 C# 中的实现方式,它们可以仅基于 byteintlongshort(及其无符号类似物),你不能使用 string 作为后备类型。