2013-04-02 58 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)); 

這裏的好處是,你讓編譯器爲你努力工作,並且方法調用和返回值都是類型安全的,提供intellisense等。

+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

有點取決於你爲什麼想要這樣做首先...我會這樣做使用Func通用,使CrazyClass仍然可以不知道的參數。

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; 
    } 
}