2015-04-01 73 views
0

我有一个模型类,它具有很少的属性,其中之一是整数列表。我在控制器中创建了这个类的一个实例,我想在这个列表中添加一些逻辑的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); 
+0

什么 “的错误”? – Ajean 2015-04-01 18:48:39

回答

3

列表例如刚刚创建实例在构造函数中

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

您可以添加一个参数的构造函数初始化列表:

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

这样,当你实例列表被初始化的对象。

+0

完美谢谢! – Newbie 2015-04-01 18:09:20

+0

@Newbie check [this](http://stackoverflow.com/help/someone-answers)。 – dario 2015-04-01 18:26:01

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 }; 
0

可以使用的读/写性能:

class A{ 

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