gpt4 book ai didi

asp.net - 使用列表查看模型

转载 作者:行者123 更新时间:2023-12-02 01:26:52 27 4
gpt4 key购买 nike

如果我用这样的列表构建 View 模型:

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>();
}
}

额外的构造函数元素实际上做了什么?

最佳答案

当您使用以下语句创建 ProductsViewModel 类的对象时:

ProductsViewModel obj = new ProductsViewModel();

它会自动实例化 ProductList。 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() 它会给出

Exception of NullReference

关于asp.net - 使用列表查看模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36617921/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com