簡體   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