2016-04-14 84 views
3

我敢肯定這可能是非常基本的,但我還沒有看到它的答案。如果我用這樣的列表構造一個視圖模型:構建一個列表視圖模型

public class ProductsViewModel 
{ 
    public bool ProductBool { get; set; } 
    public string ProductString { get; set; } 
    public int ProductInteger { get; set; } 
    public List<Product> ProductList { get; set; } 
} 

它工作正常。但我見過構建類似模型的代碼,如下所示:

public class ProductsViewModel 
{ 
    public bool ProductBool { get; set; } 
    public string ProductString { get; set; } 
    public int ProductInteger { get; set; } 
    public List<Product> ProductList { get; set; } 

    public ProductsViewModel() 
    { 
     this.ProductList = new List<Product>(); 
    } 
} 

額外構造函數元素實際上做了什麼?謝謝你的幫助。

+7

它只是初始化'ProductList'爲空集(所以它不是' null')。所以現在你可以做 - 'var model = new ProductsViewModel();模型Products.Add(新產品());'並且它不會拋出異常(否則你需要在'Add()'方法之前添加'model.ProductList = new List (); –

+1

我認爲沒有必要在構造函數中的產品列表中實例化,定義對象如'列表 ProductList objProductList = new List ProductList();'在列表中的Add()前面 –

+2

@Prabhat沒有任何意義OP顯示屬性;你展示瞭如何初始化一個新的局部變量(我猜你試圖把它分配給'ProductList'屬性)。添加一個局部變量來初始化一個類成員是沒有必要的。 – CodeCaster

回答

2

當你創建類ProductsViewModel與該語句的對象:

ProductsViewModel obj = new ProductsViewModel(); 

它會自動實例化的產品列表。在obj中的值現在是:

ProductBool = false;ProductString = null;ProductInteger = 0;ProductList = new ProductList(); 

如果你寫obj.ProductList.Count()它會給0

如果如上創建刪除此構造函數或在構造函數中的聲明和類ProductsViewModel的創建對象。在obj中的值將是:

ProductBool = false;ProductString = null;ProductInteger = 0;ProductList =null 

如果你寫obj.ProductList.Count()它會給NullReference的

異常