【问题标题】:NullReferenceException when trying to add to a list of dictionaries尝试添加到字典列表时出现 NullReferenceException
【发布时间】:2013-01-21 02:35:19
【问题描述】:

执行此代码时,我在以下几行收到 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)
            {
            }
        }
    }
}

【问题讨论】:

标签: c# .net oop list dictionary


【解决方案1】:

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

【讨论】:

  • 谢谢,就是这样。我“知道” NullReference 的含义,只是不记得正确的 C# 语法。
【解决方案2】:

当然,如果你使用更简洁的语法,用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,然后将其添加到以后可以检索的列表中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-07
    • 2022-01-22
    • 1970-01-01
    • 2011-01-22
    相关资源
    最近更新 更多