0

执行此代码时,我在这些行上收到 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);

我无法弄清楚发生了什么。我用正确的项目创建了一个字典,但是当我尝试将它添加到列表中时,我只得到一个 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)
            {
            }
        }
    }
}
4

2 回答 2

7

您的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构造函数中将其声明为局部变量。

于 2013-02-06T01:05:55.390 回答
1

当然,如果你使用更简洁的声明局部变量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然后将其添加到稍后可以检索的列表中。

于 2013-02-06T01:21:25.000 回答