列表属性使用自动实现的Getter / Setter返回'对象引用未设置为对象的实例'

时间:2014-10-21 13:27:33

标签: c#

为什么下面的C#代码允许List类型的自动实现属性,然后导致对象引用运行时错误?我意识到我可以实现getter并初始化List,但是想知道行为背后是否有原因。

class Program
{
    static void Main(string[] args)
    {
        Foo foo = new Foo();
        foo.FooList.Add(3);
    }
}

class Foo
{
    public List<int> FooList { get; set; }
}

}

2 个答案:

答案 0 :(得分:4)

您需要在Foo对象

的构造函数中初始化列表
class Foo
{
    public List<int> FooList { get; set; }

    public Foo()
    {
        FooList  = new List<int>();
    }

}

答案 1 :(得分:4)

这是一个属性,尚未实例化。您可以在类的构造函数中或在Main方法中实例化它。

class Foo
{
    public List<int> FooList { get; set; }

    public Foo()
    {
        FooList = new List<int>();
    }
}

或者在Main方法中,例如:

static void Main(string[] args)
{
    Foo foo = new Foo();
    foo.FooList = new List<int>();
    foo.FooList.Add(3);
}

或者使用C#6.0,您可以:

class Foo
{
    public List<int> FooList { get; set; } = new List<int>();

}
相关问题