C# 阅读许多元素-如何避免(…!=null)混乱?(嵌套)
我正在C#项目中使用Microsoft Linq读取一个xml文件。我通过如下方式访问xml文档中的数据:C# 阅读许多元素-如何避免(…!=null)混乱?(嵌套),c#,xml,C#,Xml,我正在C#项目中使用Microsoft Linq读取一个xml文件。我通过如下方式访问xml文档中的数据: document.Root.Element("myElement").Attribute("myAttribute").Value if (... != null) { if (... != null) { if (... != null) { if (... != null) { if (... != null) {
document.Root.Element("myElement").Attribute("myAttribute").Value
if (... != null) {
if (... != null) {
if (... != null) {
if (... != null) {
if (... != null) {
...
}
}
}
}
}
我收到警告,这可能会导致NullReferenceException
。我必须检查null
)(对于我要读取的每个元素和属性)
但是,我不希望有很多嵌套的if检查,如:
document.Root.Element("myElement").Attribute("myAttribute").Value
if (... != null) {
if (... != null) {
if (... != null) {
if (... != null) {
if (... != null) {
...
}
}
}
}
}
这很快就会变丑。在C#
中有更好的方法吗?在Swift
中,有一个名为的东西,在这种情况下是理想的。它还允许“强制展开”这些内容,这会告诉编译器这不能为null。C#中是否有等价物
谢谢大家! 您可以使用
if( ... !=null && ...!=null && ...!=null...)
或者试着抓住
您可以使用
if( ... !=null && ...!=null && ...!=null...)
或者试着抓住
你听说了吗?你可以这样写声明:
var v = document.Root?.Element("myElement")?.Attribute("myAttribute")?.Value;
因此,如果Root
为null
或Element(“myElement”)
返回null
或Attribute(“myAttribute”)
返回null
,结果将是null
你听说过吗?你可以这样写声明:
var v = document.Root?.Element("myElement")?.Attribute("myAttribute")?.Value;
因此,如果
Root
是null
或Element(“myElement”)
返回null
或Attribute(“myAttribute”)
返回null
,则结果将是null
为了避免这个链,我通常使用以下模式:
if(... == null)
break; // or continue; // or return; // depends on the context
if(... == null)
break; // or continue; // or return; // depends on the context
...
这会将此链分解为一系列空检查为了避免此链,我通常使用以下模式:
if(... == null)
break; // or continue; // or return; // depends on the context
if(... == null)
break; // or continue; // or return; // depends on the context
...
这会将此链分解为一系列空检查您的意思是像?Is
XPath
这样的选项吗?上面提到的空传播将是可行的语法<代码>a?.b?.c?.d=值您的意思是像?IsXPath
这样的选项吗?上面提到的空传播是可行的语法<代码>a?.b?.c?.d=值代码>哦,该死的,在<代码> SWIFT <代码>中,这意味着字面相反,这就是为什么我甚至没有考虑过它。一旦可以,我会接受的。谢谢哦,该死的,在<代码> SWIFT <代码>中,这意味着字面相反,这就是为什么我甚至没有考虑过它。一旦可以,我会接受的。谢谢会起作用但不是一个好方法,注意我没有投反对票。会起作用但不是一个好方法,注意我没有投反对票