2013-04-10 57 views
3

我想爲列表的每個成員調用一個函數,但將其他參數傳遞給委託。列表Foreach參數化委託

,如果我有一個名爲documents

List<string> documents = GetAllDocuments(); 

現在我需要遍歷文件,並呼籲每個條目的方法列表。我可以使用類似

documents.ForEach(CallAnotherFunction); 

這就要求CallAnotherFunction有像

public void CallAnotherFunction(string value) 
{ 
    //do something 
} 

的定義,但做到這一點,我需要在CallAnotherFunction另一個參數叫,說content,是依賴於呼叫名單。

所以,我理想中的定義是

public void CallAnotherFunction(string value, string content) 
{ 
    //do something 
} 

而且我想傳遞的內容是給ForEach呼叫

List<string> documents = GetAllDocuments(); 
documents.ForEach(CallAnotherFunction <<pass content>>); 

List<string> templates = GetAllTemplates(); 
templates.ForEach(CallAnotherFunction <<pass another content>>); 

的一部分,是有辦法,我可以做到這一點,而不必定義不同的功能,還是使用迭代器?

回答

9

使用lambda表達式而不是方法組:

List<string> documents = GetAllDocuments(); 
documents.ForEach(d => CallAnotherFunction(d, "some content")); 

List<string> templates = GetAllTemplates(); 
templates.ForEach(t => CallAnotherFunction(t, "other content")); 
+0

人爲我感到愚蠢,這是太明顯了。乾杯! – 2013-04-10 09:44:02

1

使用lambda表達式:

string content = "Other parameter value"; 
documents.ForEach(x => CallAnotherFunction(x, content));