2016-04-20 42 views
0

我有一个类商店。我需要知道什么是更好的方法,以及下面的初始化有什么不同。列表初始化构造函数或属性

class Store 
{ 
    // do we initialise List of Item here in property 
    public List<Item> Items { get; set; } = new List<Item>(); 

    public Store() 
    { 
     // we can instantiate list in constructor 
     Items = new List<Item>(); 
    } 

    public Store(string myString) 
    { 
     // lets say we have another constructor here and if this one is called 
     // than List in default constructor will not be initialised 
    } 

} 
  1. 是更好地初始化列表中的财产?
  2. 属性初始化和构造函数有什么区别?
  3. 何时调用属性初始化?
  4. 令我惊讶的是,我没有初始化List(我注释过行),并且在创建Store类的新实例时没有抛出错误System.NullReferenceException。如果我评论List实例化,为什么它没有抛出错误。我使用VS 2015,它可以自动在这个版本。

回答

1
  1. 如果您想编写更少的代码会更好。现场背后没有任何区别。
  2. 唯一的区别是,如果您在构造函数中初始化它,您可以更改初始化的顺序。在场景编译器后面,编译器将你的自动属性转换为带有后台字段的属性,并在所有构造函数的开头添加这个字段的初始化。所以,在你的代码中,你只需要在默认构造函数中覆盖Items属性。
  3. 它在构造函数中调用(在开始时)。
  4. 见第2页

也有类似的问题Difference between (auto) properties initialization syntax in C# 6

相关问题