C# 合并运算符抛出

标签 c# string c#-4.0 null-coalescing-operator null-coalescing

我有一个带有字符串属性的类。我在读取它时使用合并运算符,因为它可能为空,但它仍然抛出一个 NullRefrenceExeption。

string name = user.Section.ParentSection.Name ?? string.Empty;

更具体地说,它是 null 的“.ParentSection”,是因为它甚至没有“.name”吗?如果是这样的话,我应该先用 if block 测试“.ParentSection”吗?

我想我不明白 Coalesce 运算符的某些地方,希望有人能阐明这里出了什么问题。

最佳答案

To be more specific, its the ".ParentSection" that's null so is it because it don't even have ".name" ?

是的。

If that's the case should i test ".ParentSection" first with an if block?

是的。

关于C# 合并运算符抛出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9910023/

相关文章:

c# - Expression.Lambda 中的 Tailcall 参数

c# - 与 ListView SelectedItem 与 TextCell 命令绑定(bind)

arrays - 用于绘图的元胞数组到数值数组

c# - 如何在 WPF 或 Winforms 应用程序中使用 System.ComponentModel.DataAnnotations

string - 在 ActionScript 3.0 中是否可以获取变量名并将其转换为字符串?

c - 将受污染的变量传递给受污染的接收器

c# - 如何在 PowerShell cmdlet 中获取当前目录?

c# - 如何将消息反序列化为强类型对象,然后为该消息动态调用运行时分配的处理程序

c# - 在 nHibernate QueryOver<T> 期间无法比较字符串

C# 代码编译后的 .exe 无法运行