2

Method1()、、、、、、の6つのメソッドがあるMethod2()Method3()します。他のメソッドの1つを呼び出す別のメソッドもあります。への入力が1の場合、呼び出されます。Method4()Method5()Method6()SuperMethod(int nr)SuperMethodMethod1()

これは、switchステートメントやif-elseステートメントをスタックすることなくエレガントな方法で実行できますか?

これは私が書いている重要な製品コードではないので、パフォーマンスは問題ではないことを付け加えておきます。

4

5 に答える 5

6

デリゲートを使用でき、短いプログラムで現実世界の問題を解決するのにも興味深いものです。

    public void CollatzTest(int n)
    {
        var f = new Func<int, int>[] { i => i / 2, i => i * 3 + 1 };

        while (n != 1)
            n = f[n % 2](n);
    }

アクション、および直接メソッド参照でも機能します

    private void DelegateActionStartTest()
    {
        Action[] Actions = new Action[] { UselesstTest, IntervalTest, Euler13 };

        int nFunction = 2;

        Actions[nFunction]();
    }
于 2012-12-17T15:40:26.430 に答える
2

Method1()、Method2()... の 6 つのメソッドがあるとします。

次に、恐ろしいメソッド名があります。メソッドに適切な名前を付け (メソッドの動作や戻り値に基づいて)、. を使用して整数からメソッドへのマッピングを作成します。 Dictionary<int,Func<???>>

SuperMethod(別の恐ろしいメソッド名) は、辞書でメソッドを検索して実行します。

于 2012-12-17T15:44:49.173 に答える
1
void Method1() { Console.WriteLine("M1"); }

void Method2() { Console.WriteLine("M2"); }

void SuperMethod(int nr)
{
    var mi = this.GetType().GetMethod("Method" + nr, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
    mi.Invoke(this, null);
}
于 2012-12-17T15:40:50.197 に答える
1

静的リストまたは配列で静的クラスを使用するだけです。一定のルックアップ時間とアクセス、および整数がキーであり、連続しているため、辞書はほとんど利点を提供しません。

static class Super
{
    static void M1()
    {
    }
    static void M2()
    {
    }
    static List<Action> Actions = new List<Action>(); 
    static Super()
    {
        Actions.Add(M1);
        Actions.Add(M2); 
    }
    static void CallSupper(int nr)
    {
        try
        {
            Actions[nr - 1](); 
        }
        catch (Exception ex)
        {

        }
    }
}
于 2012-12-17T15:46:38.610 に答える
0

最初の例では、デザインを再考するかもしれません (他の人がコメントしているように)。

本当にリフレクションを使用したい場合で、クラス インスタンス内にいると仮定すると、次のようにすることができます。

void SuperMethod(int nr)
{   
    MethodInfo methodInfo = type.GetMethod("Method" + nr);
    methodInfo.Invoke(this, null);
}
于 2012-12-17T15:38:56.960 に答える