c# - 在列表 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 变量的行上,我从编译器收到一条错误消息,提示“预期类型”。有没有办法使这项工作?
解决方案
你需要一个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))
{
...
}
推荐阅读
- blazor - 如何在 Blazor 视图中显示图像
- python - 从列表中删除 Python 字符
- encryption - 简单的双向加密生成没有特殊字符的加密密钥
- c - 在 C 中删除目录
- android - 如何计算 Android 中的平均速度(Float ArrayList)?
- c# - document.GetElementsByTagName("div") 不返回子级
- python - GUI 和 AI 逻辑流程
- php - AWS PHP PDO MySQL 连接问题 SQLSTATE[HY000] [2002]
- cmake - CMake:target_link_libraries 包含为 SYSTEM 以抑制编译器警告
- c++ - 调试 linux 源代码时发生错误:将源复制到远程机器时发生异常