c# - 是否存在链式 NULL 检查之类的东西?

标签 c# .net

我有以下难看的代码:

if (msg == null || 
    msg.Content == null || 
    msg.Content.AccountMarketMessage == null || 
    msg.Content.AccountMarketMessage.Account == null ||
    msg.Content.AccountMarketMessage.Account.sObject == null) return;

有没有一种方法可以在 C# 中链接检查空值,这样我就不必检查每个单独的级别?

最佳答案

proposals in C# 6 之一将是添加一个新的 Null Propogation operator .

这将(希望)允许你写:

var obj = msg?.Content?.AccountMarketMessage?.Account?.sObject;
if (obj == null) return;

不幸的是,此时的语言中没有任何东西可以处理这个问题。

关于c# - 是否存在链式 NULL 检查之类的东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23231253/

相关文章:

.net - 文化 es-DO 的默认 DateTimeFormat.ShortDatePattern 不正确

c# - VS 2008 中未定义的 Web.config 错误

c# - MS 测试断言检查

c# - 如何使用 Rx.Net 编写条件样本组合器

c# - 字符串别名在没有 System.String 的情况下工作,但 String 不工作

c# - 在 C# .NET 中,StringDictionary 没有复制构造函数是有原因的吗?

.net - .NET CLR是否可以自动内联属性?

c# - 捕捉表格到图像

c# - 使用内置的 ASP.NET Core Web 服务器构建 .NET Core 控制台应用程序?

c# - Blazor - 在运行时更改 UI CultureInfo