【发布时间】:2019-08-29 07:04:18
【问题描述】:
我正在开发一个用户可以从商店购买商品的系统。每个用户都列在数据库中,当他们购买该商品时,应将其添加到数据库中的列表ownedItems,但是在执行代码行以添加它返回的商品时
System.NullReferenceException:对象引用未设置为实例 一个对象
userAccount 指数据库中的用户部分。这是在 !buy 命令内将项目添加到列表的位置,然后返回 null:
var userAccount = UserAccounts.GetAccount(Context.User);
userAccount.ownedItems.Add(":motorbike: motorbike");
UserAccounts.SaveAccounts();
这是在UserAccount类下定义列表的地方
public List<string> ownedItems { get; set; }
如果指定用户的userAccount 不存在,则会在此处创建列表:
private static UserAccount CreateUserAccount(ulong id)
{
var newAccount = new UserAccount()
{
ID = id,
Level = 0,
XP = 0,
RequiredXP = 150,
Bank = 50,
Cash = 50,
ownedItems = new List<string> { ":iphone: iPhone" }, //this is where ownedItems is defined
};
accounts.Add(newAccount);
SaveAccounts();
return newAccount;
}
虽然它设置为在创建userAccount 时添加“:iphone: iPhone”,但它没有。它只是将其设置为null。
public static void SaveAccounts()
{
DataStorage.SaveUserAccounts(accounts, accountsFile);
}
public static void SaveUserAccounts(IEnumerable<UserAccount> accounts, string filePath)
{
string json = JsonConvert.SerializeObject(accounts, Formatting.Indented);
File.WriteAllText(filePath, json);
}
【问题讨论】:
-
一个说
ownedItems1,另一个说ownedItems,是这样的吗?请始终包含足够的实际代码,而不仅仅是单行代码。最好是minimal reproducible example,这样我们就可以确切地看到发生了什么 -
你能提供一个minimal reproducible example吗?
-
我已经更好地格式化了代码,为上下文添加了更多代码,并删除了我在
ownedItems上写的ownedItems的错误。我不确定我是否可以提供一个最小、完整和可验证的示例,因为它涉及多个不同的类和其他代码部分才能使其工作。 -
你知道吗,What is a NullReferenceException, and how do I fix it? 是 C# stackoverflow 上最常见的问题?在发布这个问题之前你有没有尝试做任何事情?
-
是的,但它是在这里定义的,所以我不明白为什么它显示为空。
List<string> ownedItems = new List<string> { ":iphone: iPhone" },
标签: c# discord.net