21

是否可以将多个枚举组合在一起?下面是我想看到的代码示例:

enum PrimaryColors
{
   Red,
   Yellow,
   Blue
}

enum SecondaryColors
{
   Orange,
   Green,
   Purple
}

//Combine them into a new enum somehow to result in:
enum AllColors
{
   Red,
   Orange,
   Yellow,
   Green,
   Blue,
   Purple
}

不管它们是什么顺序,或者它们的后备号码是什么,我只想能够将它们组合起来。

对于上下文,这样我正在处理的程序的多个类将具有与它们所做的相关联的枚举。我的主程序将读取每个支持类中可用的所有枚举,并制作可用命令的可用枚举的主列表(枚举用于)。

编辑:这些枚举的原因是因为我的主程序正在读取要在特定时间执行的命令列表,所以我想读取文件,查看其中的命令是否与我的枚举之一相关联,并且如果是,请将其放入要执行的命令列表中。

4

4 回答 4

8

不确定我是否理解准确。但是您可以List<>像这样将所有值设为:

var allColors = new List<Enum>();

allColors.AddRange(Enum.GetValues(typeof(PrimaryColors)).Cast<Enum>());
allColors.AddRange(Enum.GetValues(typeof(SecondaryColors)).Cast<Enum>());

而不是List<Enum>你也可以使用HashSet<Enum>. 无论如何,因为您将PrimaryColoror分配SecondaryColor类型(即System.Enum),所以您会得到boxing,但这只是技术细节(可能)。

于 2012-12-06T00:16:00.040 回答
7

这些枚举的原因是因为我的主程序正在读取要在某些时间执行的命令列表,所以我想读入文件,查看其中的命令是否与我的枚举之一相关联,如果它即,将其放入要执行的命令列表中。

这似乎你不想要三种不同的enum类型,你想要一种类型(你称之为“master enum”)加上一些方法来决定某个值属于哪个子枚举。为此,您可以使用主枚举中的值集合,或switch.

例如:

enum Color
{
   Red,
   Orange,
   Yellow,
   Green,
   Blue,
   Purple
}

bool IsPrimaryColor(Color color)
{
    switch (color)
    {
    case Color.Red:
    case Color.Yellow:
    case Color.Blue:
        return true;
    default:
        return false;
    }
}

此外,您应该为enum类型使用单数名称(除非它是一个标志enum)。

于 2012-12-06T00:14:04.803 回答
2

保持简单,只使用隐式int转换,或使用System.Enum.Parse()函数:

enum PrimaryColors
{        
    Red = 0,
    Yellow = 2,
    Blue = 4
}

enum SecondaryColors
{
    Orange = 1,
    Green = 3,
    Purple = 5
}

//Combine them into a new enum somehow to result in:
enum AllColors
{
    Red = 0,
    Orange,
    Yellow,
    Green,
    Blue,
    Purple
}

class Program
{
    static AllColors ParseColor(Enum color)
    {
        return ParseColor(color.ToString());
    }
    static AllColors ParseColor(string color)
    {
        return (AllColors)Enum.Parse(typeof(AllColors), color);
    }
    static void Main(string[] args)
    {
        PrimaryColors color1=PrimaryColors.Red;
        AllColors result=(AllColors)color1;
        // AllColors.Red

        SecondaryColors color2=SecondaryColors.Green;
        AllColors other=(AllColors)color2; 
        // AllColors.Green

        AllColors final=ParseColor(PrimaryColors.Yellow);
        // AllColors.Yellow
    }
}
于 2012-12-06T00:26:52.920 回答
1

您可以从完整组派生子组。
一个例子:

enum AllColors 
{
   Red,
   Orange,
   Yellow,
   Green,
   Blue,
   Purple
}

enum PrimaryColors
{
   Red = AllColors.Red,
   Yellow = AllColors.Yellow,
   Blue = AllColors.Blue
}

enum SecondaryColors
{
   Orange = AllColors.Orange,
   Green = AllColors.Green,
   Purple = AllColors.Purple
}
于 2021-03-24T03:22:58.857 回答