为什么集合初始化会抛出NullReferenceException异常

4
以下代码会引发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. 为什么在这种情况下集合初始化器不起作用,即使Collection<string>实现了Add()方法,为什么会抛出NullReferenceException异常?
  2. 是否有可能让集合初始化器起作用,或者Items = new Collection<string>() { "foo" }是初始化它的唯一正确方式?

你尝试过在初始化时使用 new 吗? - pennstatephil
4个回答

4
感谢大家。简而言之,集合初始化器并不创建集合实例,而只是使用 Add() 方法将项目添加到现有的实例中,如果实例不存在,则会抛出 NullReferenceException 异常。
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"
                    };

2
你没有实例化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; }
}

为什么你的代码会抛出NullReferenceException异常


这并没有回答他的问题,请参见#2。 - mxmissile
@mxmissile 我更新了我的回答,请检查。 - Sriram Sakthivel

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
            };
    }
}

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 :-)
            };
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接