如何暧昧枚举值在C#中解决? [英] How are ambiguous enum values resolved in C#?

查看:213
本文介绍了如何暧昧枚举值在C#中解决?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我查了C#语言规范关于枚举的部分,但无法解释下列代码的输出:

I checked the section of the C# language specification regarding enums, but was unable to explain the output for the following code:

enum en {
    a = 1, b = 1, c = 1,
    d = 2, e = 2, f = 2,
    g = 3, h = 3, i = 3,
    j = 4, k = 4, l = 4
}

en[] list = new en[] {
    en.a, en.b, en.c,
    en.d, en.e, en.f,
    en.g, en.h, en.i,
    en.j, en.k, en.l
};
foreach (en ele in list) {
    Console.WriteLine("{1}: {0}", (int)ele, ele);
}



它输出:

It outputs:

c: 1
c: 1
c: 1
d: 2
d: 2
d: 2
g: 3
g: 3
g: 3
k: 4
k: 4
k: 4

现在,为什么会选择第三个1,第一个2和3,但是第二个4?这是未定义的行为,还是我失去了一些东西明显?

Now, why would it select the third "1", the first "2" and "3", but the second "4"? Is this undefined behavior, or am I missing something obvious?

推荐答案

这是专门记录是无证的行为。

This is specifically documented to be undocumented behaviour.

有可能是一些在编写代码的方式,最终将每一次捡了同样的事情,但的状态-us /库/ 16c1xs4z(v = vs.110)的.aspx>文档这样的:

There is probably something in the way the code is written that will end up picking the same thing every time but the documentation of Enum.ToString states this:

如果多个枚举成员具有相同的基础值,并尝试检索枚举成员名称的字符串表示基于其基础值,您的代码不应该做出哪些命名方法将返回任何假设。

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.

(我的重点)

正如评论所说,不同的.NET运行时可能会返回不同的值,但随着无证行为,整个问题是,它是容易改变无(貌似)很好的理由。它可以根据改变天气,时间,程序员的情绪,甚至在hotfix的.NET运行库。的您不能依靠无证行为

As mentioned in a comment, a different .NET runtime might return different values, but the whole problem with undocumented behaviour is that it is prone to change for no (seemingly) good reason. It could change depending on the weather, the time, the mood of the programmer, or even in a hotfix to the .NET runtime. You cannot rely on undocumented behavior.

请注意,在你的榜样,的ToString 是正是你想看看,因为你的打印的价值,这将反过来把它转换为字符串。

Note that in your example, ToString is exactly what you want to look at since you're printing the value, which will in turn convert it to a string.

如果您尝试什么做一个比较,所有的枚举值与相同的基础数值相当于你不能告诉你存储在首位的变量其中之一。

If you try to do a comparison, all the enum values with the same underlying numerical value is equivalent and you cannot tell which one you stored in a variable in the first place.

在其他也就是说,如果你这样做:

In other words, if you do this:

var x = en.a;

有没有办法事后推断,你写的 EN.A ,而不是 en.b en.c ,因为他们都比较平等的,它们都具有相同的基础价值。好吧,总之创建一个程序,读取自己的来源。

there is no way to afterwards deduce that you wrote en.a and not en.b or en.c as they all compare equal, they all have the same underlying value. Well, short of creating a program that reads its own source.

这篇关于如何暧昧枚举值在C#中解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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