我想知道在 C# Linq 或 lambda 表达式中访问属性或调用方法之前是否有更好的方法或一般规则来检查 null 结果。提前致谢。
据我了解,为了避免“对象引用未设置为对象的实例”或“在访问 CSharp 属性或调用方法之前检查 Lambda 结果中的 null”之类的异常,我应该使用“if”语句或“try/catch”像块:
var product1 = _myProductRepository.FindOne(p => p.Id == -20301);
//1. use "if" statement to let code flow continue
if(product1 != null) // to prevent exception "Object reference not set to an instance of an object."
{
int id1 = sh1.Id; // note: accessing property "Id" is safe here
Console.WriteLine("Product Id: {0}", id1);
}
//2. use "try/catch" block to let code flow continue
var product2 = _myProductRepository.FindOne(123);
var possibleItems = product2.Orders.Where(x => x.Id == -1);
List<Order> myOrderList = null;
try
{
myOrderList = possibleItems.ToList(); // note: ToList() method call is safe here
}
catch
{
myOrderList = new List<Order>();
}