繁体   English   中英

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

[英]object reference not set to instance of an object with list

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

只需在构造函数中创建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; }
 }

您可以添加一个无参数的构造函数来初始化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>();
    }
}

这样,当您实例化对象时,列表将被初始化。

原因是尚未将属性itemsForDuplication设置为任何值(它为null),但是您正在尝试对其调用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 };

您可以使用读/写属性:

class A{

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM