【发布时间】:2021-12-03 08:26:00
【问题描述】:
我的命令处理程序有错误。 System.NullReferenceException: '对象引用未设置为对象的实例。'
片段
Client.MessageReceived += HandleCommand;
完整代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Discord.Commands;
using Discord.WebSocket;
namespace DotNetNuker
{
public class CommandHandler
{
private CommandService Commands { get; set; }
private DiscordSocketClient Client { get; set; }
public async Task Init(DiscordSocketClient client)
{
this.Client = Client;
Commands = new CommandService();
await Commands.AddModulesAsync(Assembly.GetEntryAssembly(), null);
Client.MessageReceived += HandleCommand;
}
private async Task HandleCommand(SocketMessage Msg)
{
var msg = Msg as SocketUserMessage;
if (msg == null) return;
int argPos = 0;
if (!(msg.HasStringPrefix("n!", ref argPos) || msg.HasMentionPrefix(Client.CurrentUser, ref argPos))) return;
var context = new CommandContext(Client, msg);
var result = Commands.ExecuteAsync(context, argPos, null);
if (!result.IsCompleted) await context.Channel.SendMessageAsync("Failed to execute command.");
}
}
}
【问题讨论】:
-
乍一看,这行代码……
this.Client = Client;……看起来有点奇怪,因为传入的client从未使用过,而属性Client看起来像null。我猜这条线应该是……this.Client = client;……?
标签: c# .net discord discord.net