[英]Return an empty enumerable instead of getting nullReferenceException still throwing exception
I see the GetById function is returning null in this forEach which is throwing an exception, to prevent this I tried returning an empty Enumerable of that same type however I still get the System.NullReferenceException: Object reference not set to an instance of an object.
I see the GetById function is returning null in this forEach which is throwing an exception, to prevent this I tried returning an empty Enumerable of that same type however I still get the
System.NullReferenceException: Object reference not set to an instance of an object.
foreach (var categoryEntry in menus.GetById(options.OnlineOrdering.MenuId).Categories.OrderBy(i => i.Position) ?? Enumerable.Empty<MenuMenuCategory>())
You're accounting for the wrong null checking.您正在考虑错误的 null 检查。 If this is returning
null
:如果这是返回
null
:
menus.GetById(options.OnlineOrdering.MenuId)
Then this is throwing the error:然后这是抛出错误:
menus.GetById(options.OnlineOrdering.MenuId).Categories
Since you already have a null-coalescing check, you can use a null-conditional check on the expression that's failing:由于您已经进行了空合并检查,因此可以对失败的表达式使用空条件检查:
menus.GetById(options.OnlineOrdering.MenuId)?.Categories
This would cause the entire expression to evaluate to null
(never even trying to dereference the Categories
property) is GetById()
returns null
.这将导致整个表达式计算为
null
(甚至从不尝试取消引用Categories
属性)是GetById()
返回null
。 The result of that expression would then trigger the null-coalescing check you've added, and the loop should successfully iterate zero times as you intend.然后,该表达式的结果将触发您添加的空合并检查,并且循环应该按照您的意图成功迭代零次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.