使用自动实现的 Getter/Setter 列出属性返回“未将对象引用设置为对象的实例”

mar*_*247 0 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; }
}
Run Code Online (Sandbox Code Playgroud)

}

Hab*_*bib 5

它是一个属性,它还没有被实例化。您可以在类的构造函数或Main方法中实例化它。

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

    public Foo()
    {
        FooList = new List<int>();
    }
}
Run Code Online (Sandbox Code Playgroud)

或者在您的Main方法中,例如:

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

或者使用 C# 6.0 你可以这样做:

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

}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢哈比卜。您对 C# 6.0 方法的评论正是我一直在寻找的简写,很高兴知道。 (2认同)