将模型对象添加到列表失败

时间:2014-03-04 13:14:01

标签: c# asp.net

我有一个像这样的模型类

  namespace ConnectBLL.DTO.Response
{
    public class CategorySettings
    {
        public bool NeedsLoginToViewLongText { get; set; }
        public bool NeedsLoginToViewAnyDetails { get; set; }
        public bool ShowAttachment { get; set; }
        public string CategoryPageID { get; set; }
        public string TpUrl { get; set; }
    }

    public class CategorySettingsListResponse
    {
        public List<CategorySettings> CategorySettingsList { get; set; }
    }
}

我正在尝试像这样添加数据

    private readonly CategorySettings cs = new CategorySettings();
 CategorySettingsListResponse csr=new CategorySettingsListResponse();
 public string GetAllCategorySettings()
    {


            cs.NeedsLoginToViewLongText = true;
            cs.NeedsLoginToViewAnyDetails = false;
            cs.ShowAttachment = true;
            cs.CategoryPageID = "1";
            cs.TpUrl = "url";
            csr.CategorySettingsList.Add(cs);

    }

但这失败了,并给出了错误

Object reference not set to an instance of an object.

任何人都可以指出我做错了什么吗?

4 个答案:

答案 0 :(得分:2)

某处,您需要初始化CategorySettingsList

public class CategorySettingsListResponse
{
    CategorySettingsListResponse() {
        CategorySettingsList = new List<CategorySettings>();
    }

    public List<CategorySettings> CategorySettingsList { get; set; }
}

答案 1 :(得分:2)

您正在尝试在初始化之前使用List的实例。前

csr.CategorySettingsList.Add(cs);

插入:

if (csr.CategorySettingsList == null) {
    csr.CategorySettingsList = new List<CategorySettings>();
}

答案 2 :(得分:1)

您使用的是未创建的对象csCategorySettingsList,您应该在使用前创建它们:

public string GetAllCategorySettings()
{
    csr.CategorySettingsList = new ListCategorySettings<>();
    var cs = new CategorySettings
        {
           NeedsLoginToViewLongText = true,
           ...

答案 3 :(得分:1)

什么是cs?遗失了什么?

你忘了这样做:

 var cs = new CategorySettings();

另外

您需要在CategorySettingsListResponse的构造函数中实例化CategorySettingsList。