We seem to be getting all the information when the ID matches, but when there is no matching ID the program just crashes and gives us the following error.
这很有道理。给定您的代码,如果与给定的Employee
不匹配,则返回null
。因此,如果你这样做:
var employee = SearchForEmployee(1);
// Attempting to access the Id propery on a null value will throw.
Console.WriteLine(employee.Id);
然后将通过一个RE,因为返回值是null
。你需要一个空检查添加到您的代码:
var employee = SearchForEmployee(1);
if (employee != null)
Console.WriteLine(employee.Id);
或者,你可以使用C#-6空条件运算符:
var employee = SearchForEmployee(1);
Console.WriteLine(employee?.Id);
附注 - 您null
检查里面SearchForEmployee
是多余的,因为你无论如何,如果没有匹配,请返回null
。这将做到:
private Employee SearchForEmployee(int Id)
{
return (from emp in EmployeeArray
where emp.m_EmployeeId == Id
select emp).FirstOrDefault();
}
再或者,使用C#-6:
private Employee SearchForEmployee(int Id) =>
EmployeeArray.FirstOrDefault(emp => emp.m_EmployeeId == Id);
编辑:
从评论:
Looks like this: private Employee[] EmployeeArray = new Employee[50];
It is created when the windows form loads up, and it is only initialized when an employee is registered. We are using this method after atleast one employee was added.
嗯,你唯一的初始化该数组,但不包含存储在该数组内的引用。这意味着你可能有一个Employee
对象在那里初始化,但你有另外49个不是。
你有两个选择,要么修改查询到包括null
检查:
private Employee SearchForEmployee(int Id)
{
return EmployeeArray.FirstOrDefault(emp => emp != null && emp.m_EmployeeId == Id);
}
或者你可以使用一个List<Employee>
代替,这意味着它只会包含您已经添加了员工,它会随着您向其中添加更多员工而动态调整大小,从您的最终没有额外的工作。
也许,因为你返回'null'? – Backs
您如何使用此方法的返回值? –
这段代码没有任何错误(没有什么会引发异常)。如果某事调用'searchForEmployee'并尝试引用返回的'null'的属性,则会发生此异常。 –