尝试添加到字典列表时出现NullReferenceException
本文关键字:NullReferenceException 列表 字典 添加 | 更新日期: 2023-09-27 17:57:44
执行此代码时,我在以下行上得到一个NullReferenceException:
List<Dictionary<Slot, string>> slots = new List<Dictionary<Slot, string>>();
Dictionary<Slot, string> somedict = new Dictionary<Slot, string>();
somedict.Add(new Slot(), "s");
this.slots.Add(somedict);
我不知道发生了什么。我创建了一个带有正确项目的dict,但当我试图将其添加到列表中时,我只得到了一个NullReferenceException。。。。
我已经浏览MSDN和这个网站大约两个小时了,但运气不好。有人能帮我吗?我只是想把字典存储到一个列表中。
namespace hashtable
{
class Slot
{
string key;
string value;
public Slot()
{
this.key = null;
this.value = null;
}
}
class Bucket
{
public int count;
public int overflow;
public List<Dictionary<Slot, string>> slots;
Dictionary<Slot, string> somedict;
public Bucket()
{
this.count = 0;
this.overflow = -1;
List<Dictionary<Slot, string>> slots = new List<Dictionary<Slot, string>>();
Dictionary<Slot, string> somedict = new Dictionary<Slot, string>();
somedict.Add(new Slot(), "s");
this.slots.Add(somedict);
for (int i = 0; i < 3; ++i)
{
}
}
}
}
您的Bucket
构造函数正在创建一个局部变量slots
,但您正试图将somedict
添加到(未初始化的)Bucket
成员slots
中。
更换
List<Dictionary<Slot, string>> slots = new List<Dictionary<Slot, string>>();
带有
this.slots = new List<Dictionary<Slot, string>>();
(与相同)
slots = new List<Dictionary<Slot, string>>();
somedict
也会出现同样的问题。如果您不希望它是Bucket
中的类成员,请不要在那里声明它。如果这样做,请不要在Bucket
构造函数中将其声明为局部变量。
当然,如果您使用var
声明局部变量的更紧凑的语法,问题是显而易见的。。。
var slots = new List<Dictionary<Slot, string>>();
var somedict = new Dictionary<Slot, string>();
somedict.Add(new Slot(), "s");
this.slots.Add(somedict);
正如DocMax所指出的,您还没有初始化this.slots
,这可能意味着。。。
this.slots = new List<Dictionary<Slot, string>>();
var somedict = new Dictionary<Slot, string>();
somedict.Add(new Slot(), "s");
this.slots.Add(somedict);
我怀疑Bucket.somedict
字段的声明可能是多余的,因为您正在创建一个本地somedict
,然后将其添加到稍后可以检索的列表中。