简体   繁体   English

从不同的C#类访问列表对象

[英]accessing list objects from different class C#

I am trying to workout to see how I can access list items from a different class and to update the same, I have my code below for clarification. 我正在尝试锻炼以了解如何从不同的类访问列表项并更新它们,我在下面的代码中进行了澄清。

class list
{
    private List<Person> people;
    public List<Person> People
    {
       get { return people; }
       set { people = value; }
    }
}

public partial class Form2 : Form
{
    Person p = new Person();
    list l = new list();

    p.Name = textBox1.Text;
    p.Streetaddress = textBox2.Text;
    p.Email = textBox3.Text;
    p.Birthday = dateTimePicker1.Value;
    p.AdditionalNotes = textBox4.Text;

    l.People.Add(p);
    listView2.Items.Add(p.Name);
}

there is Person class which has instance variables Name, Streetaddress etc. 有Person类,它有实例变量Name,Streetaddress等。

Getting an error 得到一个错误

Nullreference exception was unhandled Nullreference异常未得到处理

Please help me.. 请帮我..

You need to instantiate the inner List<Person> when the List class is instantiated. 在实例化List类时,需要实例化内部List<Person> Otherwise it will be null. 否则它将为null。

class list
{

   private List<Person> people = new List<Person>();
   public List<Person> People
   {
       get { return people; }
       set { people = value;}
   }

}

Basically, you have defined a property People in class list but have not initialized it. 基本上,您已在类列表中定义了属性People但尚未初始化它。 Just initialize it in the constructor of list class. 只需在list类的构造函数中初始化它。

Can you try: 你能试一下吗:

class list
    {

       private List<Person> people;
       public List<Person> People
       {
           get { return people; }
           private set { people = value;}
       }

       public list()
       {
         people = new List<Person>();
       }
    }

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

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