C# 需要帮助转换为多类层次结构吗

C# 需要帮助转换为多类层次结构吗,c#,C#,为不协调编写一个bot,并希望在出错时更容易调试 我想要这个 private static void Main(string[]) args) { var client = new DiscordClient(); client.Connect(" "); var commands = new client.Services.Get<CommandService>(); commands.CreateCommand("test") .D

为不协调编写一个bot,并希望在出错时更容易调试

我想要这个

private static void Main(string[]) args)
{
    var client = new DiscordClient();
    client.Connect(" ");
    var commands = new client.Services.Get<CommandService>();
    commands.CreateCommand("test")
        .Description("This is a test command.")
        .Do(async e =>
            {
                await e.Channel.SendMessage("Test Successful!");
            });
}

我从来都不擅长使用多类,即使是类似的示例也会有所帮助。

您可以创建一个接口
IDiscordCommand
,其中包含名称、描述和运行命令的方法

public interface IDiscordCommand
{
    string Name { get; set; }
    string Description { get; set; }
    void Run(CommandEventArgs e);
}
下面是一个示例实现

public class TestCommand : IDiscordCommand
{
    public string Name { get; set; }
    public string Description { get; set; }

    public void Run(CommandEventArgs e)
    {
        e.Channel.SendMessage("Test");
    }
}
然后在您的程序上,您可以创建一个包含所有可用命令的列表,并使用
CommandService
将其注册,如下所示

namespace Console.scripts
{
    class test
    {
        commands.CreateCommand("test")
            .Description("This is a test command.)
            .Do(async e =>
                {
                    await e.Channel.SendMessage("Test Successful!");
                });
    }
}
public class Program
{
    static void Main(string[] args)
    {
        var client = new DiscordClient();
        client.Connect(" ");

        RegisterCommands(client.Services.Get<CommandService>());
    }

    public static void RegisterCommands(CommandService commandService)
    {
        var commands = new List<IDiscordCommand>();
        commands.Add(new TestCommand());

        foreach (var command in commands)
        {
            commandService.CreateCommand(command.Name)
                .Description(command.Description)
                .Do(command.Run);
        }
    }
}
公共类程序
{
静态void Main(字符串[]参数)
{
var client=new DiscordClient();
client.Connect(“”);
RegisterCommand(client.Services.Get());
}
公共静态无效注册表命令(CommandService CommandService)
{
var命令=新列表();
Add(newtestcommand());
foreach(命令中的var命令)
{
commandService.CreateCommand(command.Name)
.Description(命令.Description)
.Do(command.Run);
}
}
}

据我所知,目前我会使用CommandEventArgs事件,但在“.Do(command.run);”行中遇到了一个问题。“此异步方法缺少'wait'运算符,将同步运行”“只能将赋值、调用、增量、减量和新对象表达式用作语句”。注意:将行编辑为“.Do(async e=>command.Run);”,然后在命令类上(在本例中为
TestCommand
)将
async
添加到
Run
方法签名中。然后更改为
.Do(async e=>wait command.Run(e))
.Async在SDK之外应用时是一个未知的方法。您必须将
公共无效运行(CommandEventArgs e)
更改为
公共异步无效运行(CommandEventArgs e)
“无法等待'void'”