gpt4 book ai didi

c# - 使用LINQ创建搜索栏不断崩溃

转载 作者:行者123 更新时间:2023-12-03 16:51:25 25 4
gpt4 key购买 nike

private Employee searchForEmployee(int ID)
{
var EmployeeDetails = (from emp in EmployeeArray
where emp.m_EmployeeId == ID
select emp).FirstOrDefault();
if (EmployeeDetails != null)
{
return EmployeeDetails;
}
else
{
return null;
}
}

问题(抱歉,格式不好,我是这和Linq的新手):

当ID匹配时,我们似乎正在获取所有信息,但是当没有匹配的ID时,程序将崩溃并给出以下错误:

Additional information: Object reference not set to an instance of an object. If there is a handler for this exception, the program may be safely continued.



请帮忙!

最佳答案

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与他的 Id不匹配,则返回 null。因此,如果您这样做:
var employee = SearchForEmployee(1);

// Attempting to access the Id propery on a null value will throw.
Console.WriteLine(employee.Id);

然后,这将通过NRE,因为返回值是 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对象,但又有一个初始化的对象。

您有两个选择,可以修改查询以包括 null检查:
private Employee SearchForEmployee(int Id)
{
return EmployeeArray.FirstOrDefault(emp => emp != null && emp.m_EmployeeId == Id);
}

或者,您可以改用 List<Employee>,这意味着它只包含您已经添加的雇员,并且随着您向其中添加更多雇员,它会动态调整大小,而从头开始没有任何额外的工作。

关于c# - 使用LINQ创建搜索栏不断崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32825745/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com