查字典有困难

  • 本文关键字:字典 c# discord.net
  • 更新时间 :
  • 英文 :


所以我在引用字典时遇到了一些问题。我正在尝试制作一个经济不和机器人。我希望用户用命令设置字典!g设置,然后键入!g注册以将其Discord ID注册到词典中。

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Discord.Commands;
using Discord;
namespace Games_Bot.Modules
{
public class Commands : ModuleBase<SocketCommandContext>
{
public Dictionary<ulong, int> economy;
[Command("g setup")]
public async Task Setup()
{
economy = new Dictionary<ulong, int>();
}
[Command("g register")]
public async Task Register()
{
var userInfo = Context.User;
try
{
if (economy.ContainsKey(userInfo.Id) == false) { economy.Add(userInfo.Id, 0); }
}
catch { return; }
}
}
}

每当我尝试在Register((中引用字典时,Visual Studio都会向我抛出null错误。感谢您的帮助!

我假设您调用了Setup,这是您没有声称的。如果是这样,那么我假设为每个请求创建一个新的Commands实例。因此,您可以使用

public class Commands : ModuleBase<SocketCommandContext>
{
public static Dictionary<ulong, int> economy = new Dictionary<ulong, int>();
[Command("g register")]
public async Task Register()
{
var userInfo = Context.User;
try
{
if (economy.ContainsKey(userInfo.Id) == false) { economy.Add(userInfo.Id, 0); }
}
catch { return; }
}
}

注意static修饰符。

(我不熟悉有问题的库。我的机器人使用DSharpPlus。(

最新更新