对象引用未设置为具有列表的对象的实例

时间:2015-04-01 17:58:24

标签: c# list asp.net-mvc-4

我有一个模型类,它有很少的属性,其中一个是整数列表。我在控制器中创建了这个类的实例,我想在这个列表中添加一些逻辑上的id。这会引发以下错误。 有人可以帮我理解如何初始化列表吗?任何帮助表示赞赏,谢谢。 模型

Public class A

    {
     public int countT { get; set; }
     public int ID { get; set; }
     public List<int> itemsForDuplication { get; set; }
    }

控制器

A Info = new A();
Info.itemsForDuplication.Add(relatedItem.Id);

4 个答案:

答案 0 :(得分:3)

只需创建List的实例,例如在构造函数

public class A
{
      public A()
      {
         itemsForDuplication = new List<int>();
      }

     public int countT { get; set; }
     public int ID { get; set; }
     public List<int> itemsForDuplication { get; set; }
 }

答案 1 :(得分:1)

您可以添加无参数构造函数来初始化List:

public class A
{
    public int countT { get; set; }
    public int ID { get; set; }
    public List<int> itemsForDuplication { get; set; }

    public A()
    {
        itemsForDuplication = new List<int>();
    }
}

以这种方式实例化对象时,列表会被初始化。

答案 2 :(得分:0)

原因是属性itemsForDuplication尚未设置为任何值(它为空),但您尝试在其上调用Add方法。

解决此问题的一种方法是在构造函数中自动设置它:

public class A
{
     public int countT { get; set; }
     public int ID { get; set; }
     public List<int> itemsForDuplication { get; set; }

    public A()
    {
        itemsForDuplication = new List<int>();
    }
}

或者,如果您不使用上述解决方案,则必须在客户端代码上进行设置:

A Info = new A();
Info.itemsForDuplication = new List<int> { relatedItem.Id };

答案 3 :(得分:0)

您可以使用读/写属性:

class A{

    private List<int> itemForDuplicate;
    public List<int> ItemForDuplicate{
        get{
            this.itemForDuplicate = this.itemForDuplicate??new List<int>();
            return this.itemForDuplicate;
        }
    }
}
相关问题