为什么下面的 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)
}
它是一个属性,它还没有被实例化。您可以在类的构造函数或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)