将类添加到另一个类属性public List <class> ListOfThatClass {get;组; }

时间:2018-12-07 13:37:46

标签: c# class nullreferenceexception generic-list

头等舱

 class Tasks
{
    public List<Ck> listCk { get; set; }
}

第二类

class Ck
{
    public string CkName { get; set; }
    public string CkConentent { get; set; }
}

现在我想将Ck添加到Tasks.listCk

Tasks t = new Tasks();
Ck ck = new Ck();
ck.CkName = "s1";
ck.CkConentent = "s2";

t.listCk.Add(ck); //Here I get NullReferenceException
  

System.NullReferenceException:“对象引用未设置为对象的实例。”   MojDevnik.Tasks.listaCk.get返回null。

2 个答案:

答案 0 :(得分:0)

您需要初始化列表,可以在构造函数中或在为其赋值之前进行初始化。下面是一个如何在构造函数中执行此操作的示例。

class Tasks
{
    public List<Ck> listCk { get; set; }

    public Task() {
        listCk = new List<Ck>();
    }

}

答案 1 :(得分:0)

您需要首先实例化列表

更改此

 class Tasks
{
    public List<Ck> listCk { get; set; }
}

 class Tasks
{
    public List<Ck> listCk { get; set; } = new List<Ck>();
}

Tasks t = new Tasks();
                Ck ck = new Ck();
                ck.CkName = "s1";
                ck.CkConentent = "s2";

                t.listCk.Add(ck); *Here i get NullReferenceException*

Tasks t = new Tasks();
                Ck ck = new Ck(){listCk  = new List<Ck>()};
                ck.CkName = "s1";
                ck.CkConentent = "s2";

                t.listCk.Add(ck); *Here i get NullReferenceException*

添加一个构造函数

   class Tasks
{
    public List<Ck> listCk { get; set; }

    public Task() {
        listCk = new List<Ck>();
    }

}