【发布时间】:2021-04-14 12:19:54
【问题描述】:
考虑以下代码:
using System;
namespace Test
{
enum Foo
{
A = 1,
B = 1,
C = 1
}
public static class Program
{
public static void Main()
{
Console.WriteLine("{0}, {1}, {2}", Foo.A, Foo.B, Foo.C);
}
}
}
知道枚举只是底层的整数,我希望它是A, A, A 或C, C, C。但令人惊讶的是,它会打印出B, B, B!这种行为在 .NET Framework、.NET Core 3.x 和 .NET 5 中似乎是一致的。
为什么会选择B?
【问题讨论】:
-
你能解释一下为什么你期望这个构建的假设场景的输出是 A、A、A 还是 C、C、C?
-
根据
Enum.GetName()的文档是未定义的:If multiple enumeration members have the same underlying value, the GetName method guarantees that it will return the name of one of those enumeration members. However, it does not guarantee that it will always return the name of the same enumeration member.所以它可以在这方面做它喜欢的事情。至于“为什么”,我想你得看看实现 -
当你改变枚举中的顺序时,它仍然会打印第二个。
-
@FranzGleichmann 我希望枚举实现包含某种值到字符串的查找,其中包含第一个或最后一个声明