在c#中显式转换为枚举

时间:2012-07-21 08:13:44

标签: c# enums clr

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
}

输出为“黄色”。

4 个答案:

答案 0 :(得分:6)

它只返回基础值为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

  

如果多个枚举成员具有相同的基础值,并且您尝试根据其基础值检索枚举成员名称的字符串表示形式,则您的代码不应对该方法将返回的名称做出任何假设。例如,以下枚举定义了两个具有相同基础值的成员Shade.Gray和Shade.Grey。

     

...

     

以下方法调用尝试检索其底层值为1的Shade枚举成员的名称。该方法可以返回“Gray”或“Gray”,并且您的代码不应该对哪个字符串将做出任何假设被退回。

答案 1 :(得分:1)

.net中的每个枚举变量都映射到整数值,因此只有它才能知道要返回的类型

MSDN- enum (C# Reference)

The default underlying type of the enumeration elements is int. By default, the
first enumerator has the value 0, and the value of each successive enumerator is 
 increased by 1.

答案 2 :(得分:1)

这样的答案是 - 未定义。您可能会发现答案在不同版本之间变化,甚至在机器之间变化(不太可能)。虽然这个问题很有趣 - 但你不应该依赖于在这种情况下产生的任何特定答案。你还有很多其他方法可以做。

像:

 private enum MainColor
    {
        Red,
        Green, 
        Blue, 
    }

   private enum Color
   {
        Red = MainColor.Red,
        Green = MainColor.Green, 
        Blue = MainColor.Blue, 
        Brown = MainColor.Red, 
   }

然后您可以转回MainColor并获得明确的答案。

在我看来,它是基于某种散列列表找到它找到的第一个匹配。细节应该对您的代码无关紧要。

答案 3 :(得分:0)

而不是你的枚举尝试这个:

    private enum Color
    {  
         Red,
         Green,BLUE,black,brown = Red,gray  
    }

观察:

1) (Color)0 : Red  
2) (Color)1 : Green   
3) (Color)2 : BLUE  
4) (Color)3 : black  

所以CLR将按照它们进入枚举的顺序进行。

相关问题