Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在这个代码中可以避免多个IFs吗?_C#_If Statement - Fatal编程技术网

C# 在这个代码中可以避免多个IFs吗?

C# 在这个代码中可以避免多个IFs吗?,c#,if-statement,C#,If Statement,我有这种代码的和平。我必须检查XML中的每个级别,避免出现NULL异常。我可以改进这个代码吗 private void GetFunctionsValues(XElement x) { if (x.Element("credentials") != null) { if (x.Element("credentials").Element("faccess") != null) {

我有这种代码的和平。我必须检查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 (x.Element("credentials") != null && x.Element("credentials").Element("faccess") != null )

第一个计算为false以防止执行第二个,因此不存在null引用异常。这种行为通常被称为“短路求值”:一旦程序理解,它就可以跳过
if
,停止求值其余部分。

您可以合并一些
if()
,这仅仅是因为布尔运算具有定义的顺序,它们的操作数求值(从左到右):

而不是写这封信:

if (condition_a)
    if (condition_b)
        action();
您可以简单地使用:

if (condition_a && condition_b)
     action();

只需确保您仍然首先验证您的对象是否存在,然后执行进一步的检查。

您至少可以通过将前两个
if
s组合成一个,并将属性的选择放入
foreach
循环中的查询中,使其更加紧凑:

private void GetFunctionsValues(XElement x) 
{ 
    if (x.Element("credentials") != null
        && x.Element("credentials").Element("faccess") != null) 
    { 
        foreach (var attribute in x.Element("credentials")
                                   .Element("faccess")
                                   .Elements("access")
                                   .Select(x => x.Attribute("db_id"))
                                   .Where(x => x != null)) 
        { 
            if (int.Parse(attribute.Value) == 19) FuncPlus = true; 
        } 
    } 
} 

请参阅了解为什么可以将前两个
if
s合并为一个。

要改进它并将两个if合并,您可以尝试

private void GetFunctionsValues(XElement x)
{
    var credentialsElement = x.Element("credentials") ;
    if (credentialsElement != null && credentialsElement.Element("faccess") != null)
    {
         foreach (var access in credentialsElement.Element("faccess").Elements("access"))
         {
             if (access.Attribute("db_id") != null)
             {
                 if (int.Parse(access.Attribute("db_id").Value) == 19) FuncPlus = true;
             }
         }
     } 
}

我经常发现使用return(返回)而不是叠置(叠置)的代码更具可读性:

private void GetFunctionsValues(XElement x)
{
    if (x.Element("credentials") == null || x.Element("credentials").Element("faccess") == null) return;
    foreach (var access in x.Element("credentials").Element("faccess").Elements("access"))
    {
        if (access.Attribute("db_id") != null && int.Parse(access.Attribute("db_id").Value) == 19)
        {
            FuncPlus = true;
            return; // it seems we can leave now !
        }
    }
}

看看我在验证条件时添加的返回:我认为您不需要继续迭代。

如果是我,我会这样写:

private void GetFunctionsValues(XElement x)
{
    if (x.Element("credentials") == null
    || x.Element("credentials").Element("faccess") == null)
       return;

    bool any = 
       x
       .Element("credentials")
       .Element("faccess")
       .Elements("access")
       .Where(access => access.Attribute("db_id") != null)
       .Any(access => int.Parse(access.Attribute("db_id").Value) == 19);

    if (any)
       FuncPlus = true;
}
需要注意的关键事项:

连续的两个
if
可以通过将它们的表达式与
和&
连接来替换。例:

if (test1)
   if (test2)

// becomes

if (text1 && test2)
一个
foreach
后跟一个
if
的查询可以替换为一个LINQ
Where
query。例:

foreach (var item in collection)
   if (item.SomeProperty == someValue)
      action(item);


// becomes

collection
.Where(item => item.SomeProperty == someValue)
.ForEach(action);
在执行某些操作之前进行的测试通常最好是反向编写,以避免过度嵌套。例:

if (test1)
   if (test2)
      if (test3)
         doSomething();

// becomes

if (!(test1 || test2 || test3))
   return;

doSomething();

我相信这是最简单的选择:

    private void GetFunctionsValues(XElement x)
    {
        var el = x.XPathSelectElement(@"credentials/faccess/access[@db_id=19]");
        if(el != null)
            FuncPlus = true;
    }

XPathSelectElement
是在
System.Xml.XPath
命名空间中声明的。

我有一个扩展方法来使这些代码更具可读性:

 public static TResult Access<TSource, TResult>(
           this TSource obj, 
           Func<TSource, TResult> expression, 
           TResult defaultValue = default(TResult)) where TSource : class
    {
        if (obj == null)
        {
            return defaultValue;
        }

        return expression.Invoke(obj);
    }

if(x.Element(“凭证”)!=null和&x.Element(“凭证”).Element(“faccess”)!=null)
one if go:)这正是我要找的!它又短又漂亮。谢谢你,伊万!:-)改进不大:FuncDocGenPlus=el!=无效的现在这些台词都完美了!:)
var faccessElement = x
         .Access(y => y.Element("credentials"))
         .Access(y => y.Element("faccess"));
if (faccessElement != null) 
{
    //...
}