c# - Enum 的顺序为什么(以及如何)影响 ToString 值?

标签 c# .net c#-4.0 enums

我对枚举值的“顺序”有疑问。这有点难以解释,这就是为什么我写了一些代码:

class Program
{
    public enum EnumA
    {
        One = 1,
        Two = One,
        Three = Two,
        Four = 4
    }

    public enum EnumB
    {
        One = 1,
        Two = One,
        Four = 4,
        Three = Two
    }

    public enum EnumC
    {
        Two = One,
        Three = Two,
        Four = 4,
        One = 1
    }

    static void Main(string[] args)
    {
        Console.WriteLine("Enum A:");
        Console.WriteLine(EnumA.One);
        Console.WriteLine(EnumA.Two);
        Console.WriteLine(EnumA.Three);
        Console.WriteLine(EnumA.Four);
        Console.WriteLine();

        Console.WriteLine("Enum B:");
        Console.WriteLine(EnumB.One);
        Console.WriteLine(EnumB.Two);
        Console.WriteLine(EnumB.Three);
        Console.WriteLine(EnumB.Four);
        Console.WriteLine();

        Console.WriteLine("Enum C:");
        Console.WriteLine(EnumC.One);
        Console.WriteLine(EnumC.Two);
        Console.WriteLine(EnumC.Three);
        Console.WriteLine(EnumC.Four);
        Console.WriteLine();

        Console.ReadLine();
    }
}

输出是:

枚举 A: 二 二 二 四个

枚举 B: 三 三 三 四个

枚举 C: 一 一 一 四个

我的问题是:为什么!?我找不到输出的逻辑。很多时候都是有逻辑可寻的,所以希望大家能对这个问题有所启发。

我使用 VS2010/.Net 4.0 编译和运行代码。

最佳答案

行为被指定为“未定义”(我以为我刚才发现了一个模式,但显然没有。)documentation明确指出这一点:

If multiple enumeration members have the same underlying value and you attempt to retrieve the string representation of an enumeration member's name based on its underlying value, your code should not make any assumptions about which name the method will return.

要么使您的枚举值不同,要么显式创建从值到所需名称的映射。

关于c# - Enum 的顺序为什么(以及如何)影响 ToString 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4592536/

相关文章:

c#-4.0 - 使用tcp在同一台机器上进行进程间通信

c# - Google Analytics(分析)如何确定用户是否移动?

c# - 在不违反主键的情况下插入行的最快方法

sql - 使用 Dapper 时关闭连接

c# - 将派生类转换回基类

C# 对象大小开销

c# - 如何使用 windowhook 模拟按键

c# - OOC : What is the difference between ToList() and casting to List<T> in . 网络?

c# - 如何对齐 ItemsControl 控件 (WPF) 的列

.net - CSharpCodeProvider 从 .NET 4.0 应用程序输出 .NET 2.0 程序集