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>();
}
}
额外构造函数元素实际上做了什么?谢谢你的帮助。
它只是初始化'ProductList'为空集(所以它不是' null')。所以现在你可以做 - 'var model = new ProductsViewModel();模型Products.Add(新产品());'并且它不会抛出异常(否则你需要在'Add()'方法之前添加'model.ProductList = new List(); –
我认为没有必要在构造函数中的产品列表中实例化,定义对象如'列表 ProductList objProductList = new List ProductList();'在列表中的Add()前面 –
@Prabhat没有任何意义OP显示属性;你展示了如何初始化一个新的局部变量(我猜你试图把它分配给'ProductList'属性)。添加一个局部变量来初始化一个类成员是没有必要的。 – CodeCaster