简体   繁体   English

返回一个空的可枚举而不是获取 nullReferenceException 仍然抛出异常

[英]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.

相关问题 抛出异常而不是NullReferenceException? - The exception instead of NullReferenceException to throw? 返回空字符串,而不是System.NullReferenceException错误 - Return empty string instead of System.NullReferenceException error 返回元组<bool,string>而不是抛出异常()? - Return Tuple<bool, string> instead of throwing exception()? System.linq.Enumerable命名空间的FirstOrDefault()方法抛出NullReferenceException - FirstOrDefault() method of System.linq.Enumerable namespace throwing NullReferenceException 无限枚举是否仍然是“可枚举的”? - Is an infinite enumerable still “enumerable”? 返回一个空列表,而不是在C#中引发null异常 - Return an Empty list rather than throwing null exception in c# 返回带有错误的响应,而不是在验证管道 mediatr 3 中抛出异常 - Return response with errors instead of throwing exception in validation pipeline mediatr 3 配置AspNetCore TestServer返回500而不是引发异常 - Configure AspNetCore TestServer to return 500 instead of throwing exception OracleConnection抛出空异常 - OracleConnection is throwing empty exception XPath是正确的,并且使用NamespaceManager,但仍获取NullReferenceException - XPath is correct and using NamespaceManager but still getting NullReferenceException
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM