我有两个动物的子类(狗的最后步行日期为额外值,猫有一个坏的habbit作为额外值)在下面的代码中我创建了一只猫或一只狗
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;
}
}
现在我的问题是我做错了什么,我怎么能解决这个问题,以便能够将猫或狗添加到列表中。
答案 0 :(得分:2)
请告诉我们您的错误消息,例如它抱怨哪一行。另外,您可以尝试初始化管理员。
public AdministrationForm()
{
InitializeComponent();
animalTypeComboBox.SelectedIndex = 0;
animal = null;
admin= new Administration();
}