This repository has been archived on 2024-03-29. You can view files and clone it, but cannot push or open issues or pull requests.
FreeSR/FreeSR.Shared/Command/CommandCategory.cs
2024-01-27 21:06:07 +08:00

46 lines
1.7 KiB
C#

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;
}
}
}