2011-01-05 6 views
0

私はさまざまなメソッドの数を持つ静的クラスを持っています。C#クラスの各インスタンスには異なるメソッドが必要です

私は別のクラスを持っていますが、このクラスの各インスタンスでは、静的クラスのメソッドの1つを呼び出すメソッドが必要です。各インスタンスについて、このクラスのコンストラクタを介してどのメソッドを使用するかを指定できるようにしたい。

これを行う簡単な方法はありますか?デリゲート/インターフェイスを使用する必要がありますか?

+2

マルチキャストデリゲートから購入することができます。しかし、コードを投稿することができれば、それは役に立ちます。より良いデザインが役立つかもしれません。 – Ani

答えて

4

すべてのメソッドに同じ署名がありますか?その場合、デリゲートは確かに良いアプローチになります... 静的クラスからメソッドグループを渡すように呼び出し元を制限します。あなたが探しているものをここで

using System; 

public static class TestMethods 
{ 
    public static void Foo(int x) 
    { 
     Console.WriteLine("Foo " + x); 
    } 

    public static void Bar(int x) 
    { 
     Console.WriteLine("Bar " + x); 
    } 
} 

public class DummyClass 
{ 
    private readonly Action<int> action; 

    public DummyClass(Action<int> action) 
    { 
     this.action = action; 
    } 

    public void CallAction(int start, int end) 
    { 
     for (int i = start; i < end; i++) 
     { 
      action(i); 
     } 
    } 
} 

class Test 
{ 
    static void Main() 
    { 
     DummyClass d1 = new DummyClass(TestMethods.Foo); 
     DummyClass d2 = new DummyClass(TestMethods.Bar); 
     d1.CallAction(2, 4); 
     d2.CallAction(3, 7); 
    } 
} 
+0

この段階ではないと仮定します。 – Caustix

+1

@Causix - メソッドが同じシグネチャを持たない場合、単一のクラスは、リフレクションを使用せずにそれぞれを呼び出す方法を知らないでしょう。あなたはデリゲートではなく 'MethodInfo'を渡したいかもしれません。おそらく、あなたが達成しようとしていることを明確に見るために、いくつかのコードサンプルを投稿するべきでしょう。 –

+0

ありがとうございました。これは現在有効です。 – Caustix

1

されています:

public delegate void MyStaticMethodInvoker(params object[] values); 

public class TestStatic 
{ 
    public static void TestMethod1(params object[] values) 
    { 
     Console.WriteLine("TestMethod1 invoked"); 
    } 

    public static void TestMethod2(params object[] values) 
    { 
     Console.WriteLine("TestMethod2 invoked"); 
    } 

    public static void TestMethod3(params object[] values) 
    { 
     Console.WriteLine("TestMethod3 invoked"); 
    } 
} 

public class TestClass 
{ 
    private MyStaticMethodInvoker _targetMethod; 

    public TestClass(MyStaticMethodInvoker targetMethod) 
    { 
     _targetMethod = targetMethod; 
    } 

    public void CallTargetedStaticMethod() 
    { 
     _targetMethod.Invoke(1,2,3,4); 
    } 
} 

そしてあなたがTestClassをのインスタンスを作成することができますし、コンストラクタでターゲットに静的メソッドを定義します。それは問題がない場合は、ここではサンプルです

TestClass tc1 = new TestClass(new MyStaticMethodInvoker(TestStatic.TestMethod1)); 
tc1.CallTargetedStaticMethod(); 

TestClass tc2 = new TestClass(new MyStaticMethodInvoker(TestStatic.TestMethod2)); 
tc2.CallTargetedStaticMethod(); 

TestClass tc3 = new TestClass(new MyStaticMethodInvoker(TestStatic.TestMethod3)); 
tc3.CallTargetedStaticMethod(); 
+0

'TestStatic.TestMethod3'のメソッドグループ変換ではなく、なぜ新しいMyStaticMethodInvoker(TestStatic.TestMethod3)を使用していますか? –

+0

この場合、デリゲートが使用されていることを指摘してください。そうですね、同じ影響はTestClassを使うことです。tc1 = new TestClass(TestStatic.TestMethod1); – HABJAN

+0

これはありがたいことですが、私は現時点でそれをすべて理解していないので、今私はSkeetが言ったことに行きます。それは私に考えのための食糧を与えた。 +1 – Caustix

関連する問題