我正在尝试锻炼以了解如何从不同的类访问列表项并更新它们,我在下面的代码中进行了澄清。
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);
}
有Person类,它有实例变量Name,Streetaddress等。
收到错误
无法处理Nullreference异常
请帮帮我..
答案 0 :(得分:6)
实例化List类时,需要实例化内部List<Person>
。否则它将为null。
class list
{
private List<Person> people = new List<Person>();
public List<Person> People
{
get { return people; }
set { people = value;}
}
}
答案 1 :(得分:2)
基本上,您已在班级列表中定义了属性人员,但尚未对其进行初始化。只需在 list 类的构造函数中初始化它。
你可以尝试:
class list
{
private List<Person> people;
public List<Person> People
{
get { return people; }
private set { people = value;}
}
public list()
{
people = new List<Person>();
}
}