2013-01-22 45 views
3

我有很多功能,但我確實需要在另一個功能中運行它們。功能代碼作爲參數

我知道我可以做這樣的事情

public void Method1() 
{ 
bla bla 
} 


public void Method2() 
{ 
bla bla 
} 

public void Wrapper(Action<string> myMethod) 
     { 
     method{ 
      myMethod() 
       } 
      bla bla 
     } 

,然後用這樣的稱呼他們:

wrapper(Method1()); 

的問題是THA有時我需要運行方法1和方法2,在同一時間。他們很多。 有時一個,有時幾個在同一時間。

所以我想這將是巨大的,做這樣的事情:

Wrapper({bla bla bla; method(); bla bla; } 
{ 
method{ 
bla bla bla; 
method(); 
bla bla; 

     } 
} 

運行方法內代碼塊,和方法的參數是代碼塊。 你認爲這是可能的還是你會推薦另一種方法?

+2

http://msdn.microsoft.com/en-us/library/ms173171.aspx和http://msdn.microsoft.com/en-us/library/bb882516.aspx可能會有所幫助。 –

+0

如果你想將一個代碼塊傳遞給一個函數來執行,你想要的是一個lambda。 http://msdn.microsoft.com/en-us/library/bb397687.aspx – Patashu

回答

3

public static void Wrapper(Action<string> myMethod) 
{ 
    //... 
} 

您可以使用lambda expression指定myMethod

static void Main(string[] args) 
{ 
    Wrapper((s) => 
    { 
     //actually whatever here 
     int a; 
     bool b; 
     //.. 
     Method1(); 
     Method2(); 
     //and so on 
    }); 
} 

也就是說你不需要明確定義與所需的簽名(這裏匹配Action<string>)的方法,但你可以寫內聯的lambda表達式,做你需要的任何東西。

從MSDN:

通過使用lambda表達式,你可以寫本地函數,可以是 作爲參數傳遞或返回函數調用的值。

+0

包裝中的含義((s)=> –

+0

@RicardoPolo這相當於'動作 a =(s)=> {} ;'然後'Wrapper(a);' – horgh

+0

其中'(s)=> {}'是一個lambda表達式 – horgh

2

如果您已經有一些接受Action參數的方法,那麼您可以使用匿名方法將一堆方法組合在一起以便順序執行。

//what you have 
public void RunThatAction(Action TheAction) 
{ 
    TheAction() 
} 

//how you call it 
Action doManyThings =() => 
{ 
    DoThatThing(); 
    DoThatOtherThing(); 
} 
RunThatAction(doManyThings); 

如果依次調用方法是你做的時候,考慮讓你有接受盡可能多的操作函數...

public void RunTheseActions(params Action[] TheActions) 
{ 
    foreach(Action theAction in TheActions) 
    { 
    theAction(); 
    } 
} 

//called by 
RunTheseActions(ThisAction, ThatAction, TheOtherAction); 

你說:「在同一時間「兩次,這讓我想到了並行性。如果你想同時運行許多方法,你可以使用任務來完成。

public void RunTheseActionsInParallel(params Action[] TheActions) 
{ 
    List<Task> myTasks = new List<Task>(TheActions.Count); 
    foreach(Action theAction in TheActions) 
    { 
    Task newTask = Task.Run(theAction); 
    myTasks.Add(newTask); 
    } 
    foreach(Task theTask in myTasks) 
    { 
    theTask.Wait(); 
    } 
}