将多个枚举组合到主枚举列表中

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

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 } 

无论他们是什么顺序,或者他们的支持号码是什么,我只是希望能够将它们组合起来。

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

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

不确定我是否准确理解。 但是你可以像这样制作所有值的List<>

 var allColors = new List(); allColors.AddRange(Enum.GetValues(typeof(PrimaryColors)).Cast()); allColors.AddRange(Enum.GetValues(typeof(SecondaryColors)).Cast()); 

而不是List您也可以使用HashSet 。 在任何情况下,因为你将一个PrimaryColorSecondaryColor分配给一个类型(即System.Enum ),你得到拳击 ,但这只是一个技术细节(可能)。

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

这似乎你不想要三种不同的enum类型,你想要一种类型(你称之为“主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 )。

保持简单,只使用隐式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 } }