2016-04-14 86 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的

异常