C#在运行时构建if条件

时间:2013-06-05 04:55:58

标签: c# optimization if-statement nested-statement

我嵌套if else结构,或多或少做同样的事情。

只是一个单一的if(A&& B& C) 但我分别为条件A和C标记了D和E.

这意味着如果D为假,A应该消失而不进行评估。如果E为假,则不对C进行评估。

现在,我的代码现在类似如下:

if (D){
 if (A && B){
    if (E){
       if (C)
         { Do Something }
    } else { Do Something else}
  }
} else
  if (B) {
     if (E){
       if (C)
         { Do Something }
    } else { Do Something else}
  }
}

是否有简单的方法可以将这种复杂的结构减少到几行代码?

2 个答案:

答案 0 :(得分:1)

由于两个分支操作都是相同的,因此您可以写:

        if ((D && A && B) || (!D && B))
        {
            if (E && C)
            {
                DoSomething();
            }
            else
            {
                DoSomethingElse();
            }
        }

希望你的变量比A,B,C等更具可读性:)

答案 1 :(得分:0)

I have tested it in c since I am on unix console right now. However, logical operators work the same way for c#. following code can also be used to test the equivalance.

        #include<stdio.h>
        void test(int,int,int,int,int);
        void test1(int,int,int,int,int);
        int main()
        {
            for(int i =0 ; i < 2 ; i++)
              for(int j =0 ; j < 2 ; j++)
                 for(int k =0 ; k < 2 ; k++)
                    for(int l =0 ; l < 2 ; l++)
                       for(int m =0 ; m < 2 ; m++)
                       {
                          printf("A=%d,B=%d,C=%d,D=%d,E=%d",i,j,k,l,m);
                          test(i,j,k,l,m);
                          test1(i,j,k,l,m);
                           printf("\n");

                       }
             return 0;
        }


        void test1(int A, int B, int C, int D, int E)
        {
          if( B && (!D || A) && (!E || C))
            {
                printf("\n\ttrue considering flags");
            }
            else
            {
            printf("\n\tfalse considering flags");
            }
        }
        void test(int A, int B, int C, int D, int E)
        {
        if(D)
        {
            if( A && B)
              if(E)
                 if(C)
                {
                    printf("\n\ttrue considering flags");
                }
                else
                {
                    printf("\n\tAB !C  DE");
                }
        }
        else
        {
            if(  B)
              if(E)
                 if(C)
                {
                    printf("\n\t!D --ignore A-- BC E");
                }
                else
                {
                    printf("\n\tfalse  considering flags");
                }

        }

    }