Archived
1
0
Fork 0
forked from Moux23333/FreeSR
This repository has been archived on 2024-03-30. You can view files and clone it, but cannot push or open issues or pull requests.
FreeSR/FreeSR.Shared/Command/CommandCategory.cs

47 lines
1.7 KiB
C#
Raw Normal View History

2024-01-27 13:06:07 +00:00
namespace FreeSR.Shared.Command
{
using FreeSR.Shared.Command.Context;
using System.Reflection;
public class CommandCategory : ICommandCategory
{
private readonly Dictionary<string, CommandHandler> handlers = new Dictionary<string, CommandHandler>();
private readonly Dictionary<string, ICommandCategory> categories = new Dictionary<string, ICommandCategory>();
public void Build()
{
Type type = GetType();
foreach (MethodInfo info in type.GetMethods())
{
CommandAttribute attribute = info.GetCustomAttribute<CommandAttribute>();
if (attribute == null)
continue;
var handler = new CommandHandler(type, info);
handlers.Add(attribute.Name, handler);
}
foreach (Type info in type.GetNestedTypes())
{
CommandAttribute attribute = info.GetCustomAttribute<CommandAttribute>();
if (attribute == null)
continue;
CommandCategory category = (CommandCategory)Activator.CreateInstance(info);
category.Build();
categories.Add(attribute.Name, category);
}
}
public CommandResult Invoke(ICommandContext context, string[] parameters, uint depth)
{
if (handlers.TryGetValue(parameters[depth], out CommandHandler handler))
return handler.Invoke(this, context, parameters, depth + 1);
if (categories.TryGetValue(parameters[depth], out ICommandCategory category))
return category.Invoke(context, parameters, depth + 1);
return CommandResult.Invalid;
}
}
}