gpt4 book ai didi

c# - 为什么具有默认值的枚举在 C# 中不能按预期工作?

转载 作者:太空狗 更新时间:2023-10-29 23:12:42 27 4
gpt4 key购买 nike

我正在浏览 Jon skeet 网站上的 C# 脑筋急转弯 http://www.yoda.arachsys.com/csharp/teasers.html .为什么即使我声明了枚举中所有项目的默认值,项目“Baz”仍显示在输出中

---例如:1

class Test
{

enum Foo { Bar, Baz,bread, jam };

const int One = 1;
const int Une = 1;

static void Main()
{
Foo f = 0;
Console.WriteLine(f);
Console.ReadLine();
}
}
// output :Bar

--eg2

class Test
{
enum Foo { Bar, Baz,bread=0, jam };

const int One = 1;
const int Une = 1;


static void Main()
{
Foo f = 0;
Console.WriteLine(f);
Console.ReadLine();
}
}
//output : Bar

--eg3

class Test
{
enum Foo { Bar, Baz=0, bread=0, jam };

const int One = 1;
const int Une = 1;

static void Main()
{
Foo f = 0;
Console.WriteLine(f);
Console.ReadLine();
}
}
//output :Baz

--eg4

class Test
{
enum Foo { Bar=0, Baz=0, bread=0, jam=0};

const int One = 1;
const int Une = 1;


static void Main()
{
Foo f = 0;
Console.WriteLine(f);
Console.ReadLine();
}
}
//output:Baz

最佳答案

对于 .NET,枚举只是整数。任何时候您将它们视为名称(如 ToString()),您实际上是在说“尝试找到与整数值,并告诉我它的名称”。在这种情况下,您有多个具有相同整数值的枚举标签,因此 WriteLine 中的名称是未定义的。请注意 WriteLine 这里最终执行的是 f.ToString(),它应用上面的“查找值”逻辑。

对于--eg5,我建议:Foo f = (Foo)-1327861;。在 .NET 术语中完全有效,但不匹配任何 枚举定义。它不必。

关于c# - 为什么具有默认值的枚举在 C# 中不能按预期工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44410972/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com