2012-03-12 109 views
3

可以說我有一個方法C#通過變量引用方法?

public static void Blah(object MyMethod) { // i dont know what to replace object with 
MyMethod; // or however you would use the variable 
} 

所以基本上我需要能夠通過可變

+0

[傳遞方法作爲參數使用C#]的可能重複(http://stackoverflow.com/questions/2082615/pass-method-as-parameter-using-c-sharp) – 2012-03-12 01:35:44

回答

6

您正在尋找a delegate引用的方法。

public delegate void SomeMethodDelegate(); 

public void DoSomething() 
{ 
    // Do something special 
} 

public void UseDoSomething(SomeMethodDelegate d) 
{ 
    d(); 
} 

用法:

UseDoSomething(DoSomething); 

或者使用lambda語法(如DoSomething是一個Hello World):

UseDoSomething(() => Console.WriteLine("Hello World")); 

,還可以在表單代表快捷語法ActionFunc類型:

public void UseDoSomething(Action d) 

如果你需要從你的委託返回值(就像我的例如int),你可以使用:

public void UseDoSomething2(Func<int> d) 

注:ActionFunc提供通用的重載允許參數通過。

4

.Net框架有一堆內置的委託類型,這使得這更容易。所以,如果MyMethod需要string參數,你可以這樣做:

public static void Blah(Action<string> MyMethod) { 
    MyMethod; 
} 

,如果它需要兩個int S和返回long你會做:

public static void Blah(Func<int, int, long> MyMethod) { 
    MyMethod; 
} 

還有的Action<>版本和Func<>與不同數量您可以根據需要指定類型參數。