2013-04-10 1 views
3

목록의 모든 멤버에 대해 함수를 호출하려고하지만 대리자에 추가 매개 변수를 전달하려고합니다.List Foreach 매개 변수화 된 대리자

나는

List<string> documents = GetAllDocuments(); 

documents가 지금은 문서를 반복하고 모든 항목에 대한 방법을 호출해야합니다라는 목록이있는 경우. 내가 content라고 불리는 CallAnotherFunction의 다른 매개 변수를 필요로하지만

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

같은 정의를 가지고 이것은 CallAnotherFunction을 요구

documents.ForEach(CallAnotherFunction); 

같은 것을 사용하여 작업을 수행 할 수 있습니다, 그 호출에 따라 달라집니다 명부. 내가 정의하지 않고도이를 달성 할 수있는 방법이 있나요

그래서, 내 이상적인 정의는

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

사용 람다 표현식은 :

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

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

사람 - 나는, 바보 같은 느낌이 너무 분명했습니다. 건배! –

1

사용 람다 식 : 대신 방법 그룹의

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