c# - 检查元素是否存在或为空

标签 c#

我有这样的对象结构:

List.data[0].Contact.Mobile.MobileNumber

我需要检查 MobileNumber 是否为空。 问题是 Contact and Mobile 也可以为 null。

有没有比这样更好/更简单/更干净的方法:

(List.data[0].Contact!=null && List.data[0].Contact.Mobile!=null && List.data[0].Mobile.MobileNumber!=null)

?

最佳答案

在 C#6 中你可以试试这个

var exists = List.data[0].Contact?.Mobile?.MobileNumber != null;

关于c# - 检查元素是否存在或为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34606177/

相关文章:

c# - HttpRuntime.Cache.Remove 不删除缓存

c# - 在 Azure Function 中将 BrokeredMessage 与 ServiceBus 队列触发器结合使用

c# - 如何从 C# 中的 Main() 获取复杂的返回值

c# - 复杂的数据库操作

c# - PInvoke 使堆栈不平衡

c# - 复选框的 If-Else 语句

c# - 无需在源代码中输入我的电子邮件凭据即可发送电子邮件支持票证

c# - 将绑定(bind)属性传递给 ViewModel

c# - WPF Expander 在用户交互后忽略数据绑定(bind)

c# - 使用变量作为实体表名