我有一个带有字符串属性的类。我在读取它时使用合并运算符,因为它可能为空,但它仍然抛出一个 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/