【问题标题】:What causes this strange behaviour of an enum?是什么导致了枚举的这种奇怪行为?
【发布时间】:2015-04-01 17:27:13
【问题描述】:

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

考虑以下代码:

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
    }

我得到以下编译器错误:

无法将类型“string”隐式转换为“int”。

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

【问题讨论】:

  • 枚举是整数。当您看到一个单词 January 时,它的值为 1。(或在您的第二个示例中指定为 3)但它不能具有 g 的值。
  • 阅读stackoverflow.com/a/16039343/380384,看看你可以用enum做什么。

标签: c# enums


【解决方案1】:

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

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

语法如下:

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

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

【讨论】:

    【解决方案2】:

    这就是在C# 中实现枚举的方式,它们只能基于byteintlongshort(以及它们的无符号类似物),您不能使用string 作为支持输入。

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2011-09-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-02
        • 2012-01-05
        • 1970-01-01
        相关资源
        最近更新 更多