1

if else 構造をネストしましたが、多かれ少なかれ同じことをしています。

単純に単一の if(A && B && C) ですが、条件 A と C にそれぞれフラグ D と E があります。

つまり、D が false の場合、A は消えて評価されないはずです。E が false の場合、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}
  }
}

この複雑な構造を数行のコードに減らす簡単な方法はありますか?

4

2 に答える 2

1

両方の分岐アクションは同じなので、本質的に次のように書くことができます:

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

あなたの変数がA、B、Cなどよりも読みやすいことを願っています:)

于 2013-06-05T05:23:24.887 に答える
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");
                }

        }

    }
于 2013-06-05T05:15:06.497 に答える