首页 > 解决方案 > 在列表 C# 中动态存储多个枚举

问题描述

我想将枚举列表存储在 C# 列表中。我不想存储枚举值,而是存储枚举。我的目标是要求用户命名他们想要的一些枚举并将它们存储在列表中,以便我以后可以遍历列表。

例如,我会问他们对什么类别的食物感兴趣,他们会指定肉类、蔬菜、奶制品、水果等。根据他们想要的东西,我会告诉他们有什么可用的。

如果用户说想知道肉类和水果的类别,我会像这样打印出所有列举的肉类和水果......

beef, pork, chicken, apple, orange, banana

我的枚举将像这样定义......

enum meats {beef, pork, chicken};
enum vegetables {corn, lettuce, tomato, carrots, broccoli};
enum dairy {cheese, milk, yougurt};
enum fruits {apple, orange, banana};

由于用户选择了肉类和蔬菜,我想将其添加到 List<> 然后遍历该列表并打印出每个枚举中的所有项目。从语义上看,它看起来像......

List<enum> toPrint = new List<enum>();  //list of enum "categories"
ShopperList(meats);
ShopperList(fruits);

void ShopperList(enum category){
     toPrint.Add(category);
}

void PrintCategories(toPrint){
     foreach (enum category in toPrint){
          foreach(string name in Enum.GetNames(typeof(category)){
               Console.WriteLine(name + ", ");
          }
     }
}

在我定义 List 变量的行上,我从编译器收到一条错误消息,提示“预期类型”。有没有办法使这项工作?

标签: c#typesenums

解决方案


你需要一个List<Type>, 存储实际类型,而不是

List<Type> toPrint = new List<Type>();  //list of enum "categories"
ShopperList(typeof(meats));
ShopperList(typeof(fruits));

void ShopperList(Type category){
     toPrint.Add(category);
}

void PrintCategories(List<Type> toPrint){
     foreach (Type category in toPrint){
          foreach(string name in Enum.GetNames(category)){
               Console.WriteLine(name + ", ");
          }
     }
}

Type可以是任何东西,包括例如,string或者MyClass只是,你应该在你的循环中object进一步过滤:Type.IsEnum

foreach (Type category in toPrint.Where(x => x.IsEnum))
{
    ...
}

推荐阅读