2016-05-05 9 views
0

私はメインクラスMethodFinderクラスを持っています。私はMethodFinder経由でMainで実行するメソッド名を取得して実行したいと思います。C#のメソッドでメソッドを返して実行する

どうすればいいですか?

私がしたいことは、その後MainClassさんMainMethodで実行することができます(いくつかの基準に基づいて)方法1または方法2を返すメソッドを持つクラスです!

public MainClass 
{ 
    public void Main() 
    { 
     var methodFinder = new MethodFinder(); 
     var method = methodFinder.Find(); 

     // Execute method 
    } 

    private void Method1(){} 
    private void Method2(){} 
} 
+0

? 'string'や' MethodInfo'のようです。 –

+0

'MethodFinder'とは何ですか?既に存在しているのか、それとも実装したいのですか? – Adrian

答えて

2

あなたは限りメソッドが同じシグネチャを持っているように、このような状況でActionタイプを使用することができます。メソッドがパラメータを取った場合、Action<T>を使用できます。値が返された場合はFunc<TResult>を使用できます。この方法は、あなたがあなたの目標、または可能性Dependency Injectionを達成するためにPolymorphismを使用する場合がありますケースのようなにおいがするものの

public Action Find(SomeType someParameter) 
{ 
    if (someCondition) 
    { 
     return new Action(() => Method1()); 
    } 
    else 
    { 
     return new Action(() => Method2()); 
    } 
} 

注意。

+0

ありがとう、エリック。まさに、私はここでも悪いデザインのにおいがします! – Vahid

1

これを行うか、Reflectionを使用してより動的にすることができます。

public class MethodFinder 
{ 
    public delegate void MethodSignature(); 

    //these can live whereever and even be passed in 
    private static void Method1() => Debug.WriteLine("Method1 executed"); 
    private static void Method2() => Debug.WriteLine("Method2 executed"); 

    //maintain an array of possibilities or soemthing. 
    //perhaps use reflection instead 
    private MethodSignature[] methods = new MethodSignature[] { Method1, Method2 }; 

    public MethodSignature FindByName(string methodName) 
     => (from m in methods 
      where m.Method.Name == methodName 
      select m).FirstOrDefault(); 
} 

使用法: `.Find()`は何を返している

var methodFinder = new MethodFinder(); 
var method = methodFinder.FindByName("Method2"); 
method(); //output: "Method2 executed" 
+1

ありがとう、私もこれを試してみます。 – Vahid

関連する問題