我有这种安宁的代码。我必须检查 XML 中的每个级别以避免 NULL 异常。我可以改进这段代码吗?
private void GetFunctionsValues(XElement x)
{
if (x.Element("credentials") != null)
{
if (x.Element("credentials").Element("faccess") != null)
{
foreach (var access in x.Element("credentials").Element("faccess").Elements("access"))
{
if (access.Attribute("db_id") != null)
{
if (int.Parse(access.Attribute("db_id").Value) == 19) FuncPlus = true;
}
}
}
}
}
最佳答案
您可以将两个嵌套的 if
合并为一个:
if (x.Element("credentials") != null && x.Element("credentials").Element("faccess") != null )
第一个评估为 false 会阻止第二个的执行,因此不存在空引用异常。这种行为通常称为“短路求值”:程序很快就会理解它可以跳过 if
,它会停止对剩余部分求值。
关于c# - 是否可以在这段代码中避免使用多个 IF?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11983531/