将多个枚举组合成主枚举列表 [英] Combine multiple enums into master enum list

查看:151
本文介绍了将多个枚举组合成主枚举列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 枚举PrimaryColors 
{
Red,
黄色,
蓝色
}

枚举SecondaryColors
{
橙色,
绿色,
紫色
}

//将它们组合成一个新的枚举,导致:
枚举AllColors
{
红色,
橙色,
黄色,
绿色,
蓝色,
紫色
}

$ p

对于上下文,这是这样的我正在开发的一个程序的多个类将具有与它们相关的枚举。我的主要程序将会读取每个支持类的所有枚举,并列出可用命令的可用枚举的主列表(枚举)。



编辑:
这些枚举的原因是因为我的主程序正在读取要在特定时间执行的命令列表,所以我想在文件中读取,看看它中的命令是否与我的枚举,如果是的话,把它放在执行的命令列表中。

解决方案

不知道我明白了。但是您可以使用以下所有值的列表<>

  var allColors = new List&Enum>(); 

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

而不是列表<枚举> 也可以使用 HashSet< Enum> 。无论如何,由于您将 PrimaryColor SecondaryColor 分配给类型(即 System.Enum ),你得到拳击,但这只是一个技术细节(可能)。


Is it possible to combine multiple enums together? Below is code sample of what I would like to see:

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
}

It does not matter what order they are, or what their backing numbers are, I just want to be able to combine them.

For context, this is so that multiple classes for a program I am working on would have enums associated with what they do. My main program would read all of the enums available from each of the support classes and make a master list of available enums of available commands (the the enums are for).

Edit: The reason for these enums is because my main program is reading in a list of commands to perform at certain times, and so I want to read in the file, see if the command in it is associated with one of my enums, and if it is, put it into a list of commands to perform.

解决方案

Not sure I understand precisely. But you can make a List<> of all the values like this:

var allColors = new List<Enum>();

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

Instead of List<Enum> you could also use HashSet<Enum>. In any case, because you assign a PrimaryColor or SecondaryColor to a class type (namely System.Enum), you get boxing, but that's just a technical detail (probably).

这篇关于将多个枚举组合成主枚举列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆