2013-04-02 8 views
13
이 같은 외부 방법을 실행하는 클래스를 갖고 싶어

:이 가능위임 - C#

class CrazyClass 
{ 
    //other stuff 

    public AnyReturnType Execute(AnyKindOfMethod Method, object[] ParametersForMethod) 
    { 
    //more stuff 
    return Method(ParametersForMethod) //or something like that 
    } 
} 

를? 메서드 서명을받는 대리자가 있습니까?

+1

당신은 어떻게 그것을 어떤 매개 변수를 전달할 알 수 있습니까? 이 매개 변수의 수와 유형에 관한 잘못된 생각하면 어떤 일이 발생 하는가? – Servy

답변

26

당신은 Func<T> 및 폐쇄하여이에게 다른 방식으로 작업을 수행 할 수 있습니다

public T Execute<T>(Func<T> method) 
{ 
    // stuff 
    return method(); 
} 

호출자는 다음을 구현하는 클로저를 사용할 수 있습니다

var result = yourClassInstance.Execute(() => SomeMethod(arg1, arg2, arg3)); 

여기 장점은 컴파일러를 할 수 있다는 것입니다 당신을 위해 열심히 일을하고, 메소드 호출 및 반환 값은 당신이 반사를 사용하는 것이 더 낫다 생각하는 모든 안전 유형, 제공 인텔리 등

+1

즉 .... 너무 분명하다. –

+0

우리는 CrazyClass의 생성자에서이 작업을 수행 할 수 있습니까? 그렇다면 어떻게? – toddmo

+0

@toddmo - 당신은 당신이 그렇게 원한다면 CrazyClass 제네릭해야 할 것입니다. –

0

있습니다 이 경우, 당신은 얻을 것이다 당신은 문제가 요구 정확하게 - (정적 또는 인스턴스) 어떤 방법, 어떤 매개 변수 :

public object Execute(MethodInfo mi, object instance = null, object[] parameters = null) 
{ 
    return mi.Invoke(instance, parameters); 
} 

그것은 System.Reflection.MethodInfo 클래스의합니다.

3

은 일종의 당신이 처음에이 일을하려는 이유 ... 나는 CrazyClass 여전히 매개 변수의 무지 될 수 있도록 제네릭 Func을 사용하여이 작업을 수행 할에 따라 달라집니다.

class CrazyClass 
{ 
    //other stuff 

    public T Execute<T>(Func<T> Method) 
    { 
     //more stuff 
     return Method();//or something like that 
    } 


} 

class Program 
{ 
    public static int Foo(int a, int b) 
    { 
     return a + b; 
    } 
    static void Main(string[] args) 
    { 
     CrazyClass cc = new CrazyClass(); 
     int someargs1 = 20; 
     int someargs2 = 10; 
     Func<int> method = new Func<int>(()=>Foo(someargs1,someargs2)); 
     cc.Execute(method); 
     //which begs the question why the user wouldn't just do this: 
     Foo(someargs1, someargs2); 
    } 
} 
0
public static void AnyFuncExecutor(Action a) 
{ 
    try 
    { 
     a(); 
    } 
    catch (Exception exception) 
    { 
     throw; 
    } 
}