引用字典时遇到问题

时间:2021-07-01 01:27:25

标签: c# discord.net

所以我在引用字典时遇到了一些麻烦。我正在尝试制作一个经济不和谐机器人。我希望用户使用命令 !g setup 设置字典,然后输入 !g register 将他们的 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 error。任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:0)

我假设您调用了 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。)

相关问题