NullReferenceException while using List
本文关键字:List using while NullReferenceException | 更新日期: 2023-09-27 17:56:17
我想刷新列表框,但我得到了这个 NullReference,我不想创建一个动物并将其添加到列表中。你们能帮帮我吗?
public void UpdateForm()
{
if (administration.Animals != null)
{
List<string> reservedAnimals = new List<string>();
List<string> notReservedAnimals = new List<string>();
lbReserved.Items.Clear();
foreach (Animal a in administration.Animals)
{
if (a.IsReserved == true)
{
reservedAnimals.Add(a.ToString());
}
}
}
administration
null
- 这就是您在此行中接收异常的方式。您应该在某个地方启动administration
,例如:
administration = new YourType();
很难写更多,因为你没有提供足够的代码。
管理未初始化或为空。
使用前证明是否为空:
if (administration == null)
{
administration = new TypeOfAdministration();
}
所以你的代码应该看起来像这样:
public void UpdateForm()
{
if (administration == null)
{
administration = new TypeOfAdministration();
}
if (administration.Animals != null)
{
List<string> reservedAnimals = new List<string>();
List<string> notReservedAnimals = new List<string>();
lbReserved.Items.Clear();
foreach (Animal a in administration.Animals)
{
if (a.IsReserved == true)
{
reservedAnimals.Add(a.ToString());
}
}
}
}