gpt4 book ai didi

c# - C# 中枚举的行为

转载 作者:太空宇宙 更新时间:2023-11-03 21:51:58 24 4
gpt4 key购买 nike

 class MainClass
{
static void Main(String[] args)
{
Fruits f =Fruits.Banana;
Console.WriteLine("Fruit={0}",f);
Console.Read();
}

private enum Fruits
{
Banana=0,
Apple=0,
Orange=0,
Cherries
}

}

以上代码给出输出:Fruit=Apple

如果我在枚举中将 Banana 的值更改为 0 以外的任何值,则输出为 Banana。我的问题是,为什么在第一种情况下,输出是 Apple 而不是 OrangeBanana 本身?

最佳答案

在内部,枚举非常像具有单个内部字段的 struct - 具有与枚举的基本类型相同的类型(此处为 int),它存储值。

就枚举而言,就是这样。它没有任何其他存储空间 - 它不知道如何它是如何构建的 - 无论是通过使用枚举中的命名值,还是通过从基类型强制转换,或任何其他方式。

因此,当您请求字符串表示时,除了获取数值并尝试在其枚举成员中找到与该值匹配的名称之外,它没有其他信息可以继续。

我不确定是否 定义如果多个成员具有相同的数值,将选择哪个值,但它必须选择 某物,并且它至少看起来 一致


事实上,Enum.ToString()说:

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# - C# 中枚举的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14066982/

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