4

给定代码:

from i in this.GridViewFoo.SelectedItems
select new EmployeeEntity
{
    EmployeeID = (i as EmployeeDto).EmployeeID,
    Email = this.GetAllEmail((i as EmployeeDto).Email, (i as EmployeeDto).SecondaryEmails),
    EmployeeNumber = (i as EmployeeDto).EmployeeNumber,
    FirstName = (i as EmployeeDto).FirstName,
    LastName = (i as EmployeeDto).LastName
}

在安全转换之后,(i as EmployeeDto)我可能会收到 NullReferenceException。我怎样才能确保代码的安全性,而不是用大量的空检查使他超负荷?

解决方案概述:

我做了一些测试来断言解决方案是否有效。两者都运行良好并带来相同的结果,您可以在此处查看。之后我用OfTypeSolutionletSolution做了一些性能测试。

由于 OfType 解决方案的平均时间更好,这就是答案!

4

2 回答 2

10

您可以在:之前使用OfTypeSelect

from i in this.GridViewFoo.SelectedItems.OfType<EmployeeDto>()
select new EmployeeEntity
{
    EmployeeID = i.EmployeeID,
    Email = this.GetAllEmail(i.Email, i.SecondaryEmails),
    EmployeeNumber = i.EmployeeNumber,
    FirstName = i.FirstName,
    LastName = i.LastName
}

它只会为您提供EmployeeDto来自的类型项目,SelectedItems因此无需进行强制转换和空值检查。

于 2012-09-19T15:22:26.337 回答
2
from si in this.GridViewFoo.SelectedItems
let i = si as EmployeeDto
where i != null
select new EmployeeEntity
{
    EmployeeID = i.EmployeeID,
    Email = this.GetAllEmail(i.Email, i.SecondaryEmails),
    EmployeeNumber = i.EmployeeNumber,
    FirstName = i.FirstName,
    LastName = i.LastName
}
于 2012-09-19T15:27:42.597 回答