引用字典时遇到问题
Having trouble referencing a dictionary
所以我在引用字典时遇到了一些问题。我正在尝试制作一个经济不和谐的机器人。我希望用户使用命令 !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。感谢您的帮助!
我假设您调用了 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。)
所以我在引用字典时遇到了一些问题。我正在尝试制作一个经济不和谐的机器人。我希望用户使用命令 !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。感谢您的帮助!
我假设您调用了 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。)