繁体   English   中英

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

[英]Why Collection Initialization Throws NullReferenceException

以下代码抛出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" }是唯一正确的初始化方法?

多谢你们。 由于摘要集合初始化程序不创建集合本身的实例,而只是使用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"
                    };

在你的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
            };
    }
}

你从未实例化过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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM