为什么集合初始化会引发NullReferenceException

时间:2014-05-28 14:57:03

标签: c# .net collections nullreferenceexception duck-typing

以下代码抛出NullReferenceException

internal class Foo
{
    public Collection<string> Items { get; set; } // or List<string>
}

class Program
{
    static void Main(string[] args)
    {
        new Foo()
            {
                Items = { "foo" } // throws NullReferenceException
            };
    }
}
  1. 为什么收集initiliazers在这种情况下不起作用,虽然Collection<string>实现了Add()方法,为什么抛出NullReferenceException?
  2. 是否可以让集合初始化程序正常工作,或者Items = new Collection<string>() { "foo" }是初始化它的唯一正确方法吗?

4 个答案:

答案 0 :(得分:3)

谢谢你们。总结集合初始化程序不会创建集合本身的实例,而只是使用Add()将项目添加到existant实例,如果实例不存在则抛出NullReferenceException

1

internal class Foo
{    
    internal Foo()
    {
        Items  = new Collection<string>();
    }
    public Collection<string> Items { get; private set; }
}

var foo = new Foo()
                {
                    Items = { "foo" } // foo.Items contains 1 element "foo"
                };

2

   internal class Foo
    {    
        internal Foo()
        {
            Items  = new Collection<string>();
            Items.Add("foo1");
        }
        public Collection<string> Items { get; private set; }
    }

    var foo = new Foo()
                    {
                        Items = { "foo2" } // foo.Items contains 2 elements: "foo1", "foo2"
                    };

答案 1 :(得分:1)

Foo构造函数中,您要初始化集合。

internal class Foo
{
    public Foo(){Items = new Collection(); }
    public Collection<string> Items { get; set; } // or List<string>
}

class Program
{
    static void Main(string[] args)
    {
        new Foo()
            {
                Items = { "foo" } // throws NullReferenceException
            };
    }
}

答案 2 :(得分:1)

您从未实例化Items。试试这个。

new Foo()
    {
        Items = new Collection<string> { "foo" }
    };

回答第二个问题:您需要添加构造函数并在那里初始化Items

internal class Foo
{    
    internal Foo()
    {
        Items  = new Collection<string>();
    }
    public Collection<string> Items { get; private set; }
}

Why your code throws NullReferenceException

答案 3 :(得分:0)

声明了

Foo.Items,但从未分配Collection的实例,因此.Itemsnull

修正:

internal class Foo
{
    public Collection<string> Items { get; set; } // or List<string>
}

class Program
{
    static void Main(string[] args)
    {
        new Foo()
            {
                Items = new Collection<string> { "foo" } // no longer throws NullReferenceException :-)
            };
    }
}