gpt4 book ai didi

c# - 在 C# 中显式转换为枚举

转载 作者:行者123 更新时间:2023-11-30 14:00:14 24 4
gpt4 key购买 nike

CLR 如何确定应将零转换为哪种颜色?

internal static class Test
{
private static void Main()
{
Console.WriteLine((Color)0);
}

private enum Color
{
Red,
Green = Red
}
}

使用此颜色的定义“红色”将被输出。

如果我们使用其他定义,结果真的很有趣。

private enum Color
{
Red,
Green = Red,
Blue = Red,
Yellow = Red
}

输出为“绿色”。

另一种定义:

private enum Color
{
Red,
Green = Red,
Blue,
Yellow = Red
}

输出为“黄色”。

最佳答案

它只返回一个基础值为 0 的 Color 值。这与 Color.RedColor.Green 的值相同。

从根本上说,您的枚举被破坏了,因为 RedGreen 是相同的值。你根本无法区分它们。

Color red = Color.Red;
Color green = Color.Green;
Console.WriteLine(red == green); // True
Console.WriteLine(red.ToString() == green.ToString()); // True

我不知道是否有关于 ToString 返回“红色”或“绿色”的任何保证 - 但如果你遇到相关的情况,你应该以不同的方式描述你的枚举.

编辑:来自 documentation :

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. For example, the following enumeration defines two members, Shade.Gray and Shade.Grey, that have the same underlying value.

...

The following method call attempts to retrieve the name of a member of the Shade enumeration whose underlying value is 1. The method can return either "Gray" or "Grey", and your code should not make any assumptions about which string will be returned.

关于c# - 在 C# 中显式转换为枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11590590/

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