为什么(以及如何)不枚举的顺序影响的ToString值? [英] Why (and how) does the order of an Enum influence the ToString value?

查看:254
本文介绍了为什么(以及如何)不枚举的顺序影响的ToString值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在有问题的枚举值的命令。这是一个有点难以解释,这就是为什么我写了一些code:

Hey guys, I've been having problems with the "order" of the values of an enum. It's a little difficult to explain, that's why I wrote up some code:

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();
    }
}

的输出是:

枚举答: 二 二 二 四

Enum A: Two Two Two Four

枚举B: 三 三 三 四

Enum B: Three Three Three Four

枚举C: 一 一 一 四

Enum C: One One One Four

我的问题是:为什么!?我无法找到逻辑到输出。在大多数情况下有一定的逻辑被发现,所以我希望你们可以照一些轻这个问题。

My question is: WHY!? I can't find the logic to the output. Most of the time there is some logic to be found, so I hope you guys can shine some light on this issue.

我用VS2010 / .NET 4.0编译并运行code。

I used VS2010 / .Net 4.0 to compile and run the code.

推荐答案

中指定的行为是未定义(我想我发现了一个模式,就像现在,但显然不是。)本的文档明确要求这一点:

The behaviour is specified to be "undefined" (I thought I'd spotted a pattern just now, but apparently not.) The documentation explicitly calls this out:

如果多个枚举成员具有相同的潜在价值,并尝试获取字符串再枚举成员的名字是根据它的潜在价值presentation,你的code不应该做出哪些命名方法,任何假设会回来。

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.

无论是让你的枚举值显着,或明确创建值映射到所需的名称。

Either make your enum values distinct, or explicitly create a map from value to desired name.

这篇关于为什么(以及如何)不枚举的顺序影响的ToString值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆