avo*_*iva 0 .net c# oop dictionary list
执行此代码时,我在这些行上得到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);
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚发生了什么.我用正确的项创建了一个dict,但是当我尝试将它添加到列表中时,我只得到一个NullReferenceException ....
我一直在寻找MSDN和这个网站大约2个小时,但没有运气.谁能帮我吗?我只是想将一个字典存储到一个列表中.
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)
{
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
您的Bucket
构造函数正在创建一个局部变量,slots
但您正在尝试添加 somedict
到(未初始化的)Bucket
成员slots
.
更换
List<Dictionary<Slot, string>> slots = new List<Dictionary<Slot, string>>();
Run Code Online (Sandbox Code Playgroud)
同
this.slots = new List<Dictionary<Slot, string>>();
Run Code Online (Sandbox Code Playgroud)
(与之相同)
slots = new List<Dictionary<Slot, string>>();
Run Code Online (Sandbox Code Playgroud)
您将遇到同样的问题somedict
.如果你不是故意成为班级成员Bucket
,请不要在那里宣布.如果这样做,请不要在Bucket
构造函数中将其声明为局部变量.