2016-09-12 7 views
5

コード内に真理値表を似せる簡単な方法はありますか?以下のようにそれは、2つの入力および4つの結果を持っています真理値表に単純に似せる方法はありますか?

enter image description here

私の現在のコードです:つまり、私は配列を使用することをお勧め

private void myMethod(bool param1, bool param2) 
{ 
    Func<int, int, bool> myFunc; 
    if (param1) 
    { 
     if (param2) 
      myFunc = (x, y) => x >= y; 
     else 
      myFunc = (x, y) => x <= y; 
    } 
    else 
    { 
     if (param2) 
      myFunc = (x, y) => x < y; 
     else 
      myFunc = (x, y) => x > y; 
    } 
    //do more stuff 
} 
+3

「真理値表」と呼ばれます。 –

+0

あなたはその方向に向いているように、「ステートマシン」という用語を参照したいかもしれません。 – Stefan

+0

現在の実装で何が問題になっていますか? – slawekwin

答えて

5

// XOR truth table 
    bool[][] truthTable = new bool[][] { 
    new bool[] {false, true}, 
    new bool[] {true, false}, 
    }; 

...

private void myMethod(bool param1, bool param2, bool[][] table) { 
    return table[param1 ? 0 : 1][param2 ? 0 : 1]; 
    } 
+2

'bool'で配列をインデックスできません – Lee

+0

@Lee:ありがとう、私は(' C# 'は' C 'ではありません)、ternaty演算子が必要です –

0
public int myTest(bool a, bool b) 
{ 
    if(!b) 
    return 3; 
    return a ? 1 : 2; 
} 
+0

私はOPがより汎用的な解決策を探していると信じています –

0

あなたのコードを簡素化するために、あなたは、事前定義された配列内の値のインデックスのビットとしてparam1param2を使用することができます。

private void myMethod(bool param1, bool param2) 
{ 
    Func<int, int, bool>[] myFuncs = { 
     (x, y) => x > y, 
     (x, y) => x < y, 
     (x, y) => x <= y, 
     (x, y) => x >= y 
    }; 

    int index = (param1 ? 2 : 0) + (param2 ? 1 : 0); 
    Func<int, int, bool> myFunc = myFuncs[index]; 
    //do more stuff 
} 

しかし、もちろんのシンプルさと可読性のは、読者の目にあります。

paramXfalseの場合、index0になります。両方ともtrueの場合、index3などとなります。

関連する問題