将动物/狗/猫添加到动物列表会导致NullReferenceException
本文关键字:NullReferenceException 列表 添加 | 更新日期: 2023-09-27 18:25:40
在下面的代码中,我有两个子类的动物(狗的最后一次散步日期作为额外值,猫的坏习惯作为额外值),我创建了一只猫或一只狗
public partial class AdministrationForm : Form
{
private Animal animal;
private Administration admin;
public AdministrationForm()
{
InitializeComponent();
animalTypeComboBox.SelectedIndex = 0;
animal = null;
}
private void createAnimalButton_Click(object sender, EventArgs e)
{
if(animalTypeComboBox.SelectedItem == "Dog")
{
SimpleDate dateBirth = new SimpleDate(ttbdateBirth.Value.Day,
ttbdateBirth.Value.Month,
ttbdateBirth.Value.Year);
SimpleDate dateLast1 = new SimpleDate(dateLast.Value.Day, dateLast.Value.Month, dateLast.Value.Year);
Animal animal = new Dog(Convert.ToString(tbId.Text), dateBirth, tbName.Text, dateLast1);
admin.Add(animal);
}
if (animalTypeComboBox.SelectedItem == "Cat")
{
SimpleDate dateBirth = new SimpleDate(ttbdateBirth.Value.Day, ttbdateBirth.Value.Month, ttbdateBirth.Value.Year);
Animal animal = new Cat(Convert.ToString(tbId.Text), dateBirth, tbName.Text, tbBad.Text);
admin.Add(animal);
}
}
}
创建后,我将其发送到一个管理类,该类用于将这只狗或猫添加到动物列表中,但如标题中所述,我收到了NullReference错误。应该添加猫或狗的类如下:
class Administration
{
private List<Animal> animals;
public List<Animal> Animals { get { return new List<Animal>(animals); } }
public Administration ()
{
animals = new List<Animal>();
}
public bool Add(Animal animal)
{
foreach (Animal dog in animals)
{
if(animal.ChipRegistrationNumber == dog.ChipRegistrationNumber)
{
MessageBox.Show("dog already added");
break;
}
}
foreach (Animal cat in animals)
{
if(animal.ChipRegistrationNumber == cat.ChipRegistrationNumber)
{
MessageBox.Show("dog already added");
break;
}
}
return true;
}
}
现在我的问题是我做错了什么,我该如何解决这个问题,以便我能够将猫或狗添加到列表中。
请告诉我们您的错误消息,例如它抱怨的是哪一行。另外,您可以尝试初始化管理员。
public AdministrationForm()
{
InitializeComponent();
animalTypeComboBox.SelectedIndex = 0;
animal = null;
admin= new Administration();
}