[英]C# enum reflection?
Creating a bot with a command grouping function for organization and formatting. 创建具有命令分组功能的机器人以进行组织和格式化。
I was thinking of creating a public enum with each group option like 我当时想用每个组选项创建一个公共枚举,例如
public enum CommandGroups
{
Information,
Admin,
Owner,
etc
}
Then defining it with a public object within the command creation 然后在命令创建中使用公共对象定义它
public Command SetGroup(CommandGroups group)
{
this.group = group;
return this;
}
So when issuing a help command, something like this would return, granted after some formatting 因此,当发出帮助命令时,将在格式化后返回类似这样的内容
Information: about, stats
Admin: kick, ban, mute
Owner: reload
The problem that I thought is, can you even use reflection on an enum like this? 我认为的问题是,您是否可以在这样的枚举上使用反射? Or should I try a different way?
还是应该尝试其他方式?
Enums has a toString method, you should be fine using it 枚举有一个toString方法,使用它应该没问题
https://msdn.microsoft.com/en-us/library/16c1xs4z(v=vs.110).aspx https://msdn.microsoft.com/zh-CN/library/16c1xs4z(v=vs.110).aspx
Looks like you need something like this to generate the list of enums 看起来您需要这样的东西才能生成枚举列表
foreach (string cmdGroup in Enum.GetNames(typeof(CommandGroups)))
{
// ... print(cmdGroup);
}
That would get you 那会让你
Information 信息
Admin 管理员
Owner 所有者
Any reason to not just define objects and specify the group you are using through a class with a name? 是否有理由不只是定义对象并通过带有名称的类指定正在使用的组?
You have the benefit of having a much simpler and easier to follow design, and you can store the commands without any additional magic 您的好处是设计简单易行,而且可以存储命令而无需任何其他操作
public class Command
{
public int Id {get;set;}
public string Name {get;set;}
}
public class CommandGroup
{
public string Name {get;set;}
public IEnumerable<Commands> Commands {get;set;}
}
public class CommandGroupLookup
{
public CommandGroupLookup()
{
//initialize from database or wherever
}
private readonly Dictionary<string,CommandGroup> _commandGroup;
public Command LookupGroup( string lookupCommandGroup )
{
return _commandGroup[lookupCommandGroup];
}
}
Consider storing all your Command objects in something like a Dictionary<CommandGroups, List<Command>>
. 考虑将所有Command对象存储在
Dictionary<CommandGroups, List<Command>>
。 Then, assuming your Command class has a Name
property on it that exposes the verbs such as "about", "kick", "ban", etc., you could do: 然后,假设您的Command类具有一个
Name
属性,该属性显示诸如“ about”,“ kick”,“ ban”等动词,则可以执行以下操作:
// assuming "groups" is the dictionary:
foreach (var kvp in groups)
{
Console.WriteLine("{0}: {1}", kvp.Key, string.Join(", ", kvp.Value.Select(x => x.Name).ToArray()));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.