列出Foreach参数化的委托 [英] List Foreach parameterized delegate
问题描述
我试图为列表的每个成员调用一个函数,但将其他参数传递给委托.
I am trying to invoke a function for every member of a list, but pass additional parameters to the delegate.
如果我有一个名为 documents
List<string> documents = GetAllDocuments();
现在,我需要遍历文档并为每个条目调用一个方法.我可以使用类似
Now I need to iterate over the documents and call a method for every entry. I can do it using something like
documents.ForEach(CallAnotherFunction);
这将要求 CallAnotherFunction
具有类似
public void CallAnotherFunction(string value)
{
//do something
}
但是,我需要在 CallAnotherFunction
中调用另一个参数,例如 content
,该参数取决于调用列表.
However, I need another parameter in CallAnotherFunction
called, say content
, that is dependent on the calling list.
所以,我的理想定义是
public void CallAnotherFunction(string value, string content)
{
//do something
}
我想将内容作为ForEach通话的一部分传递
And I would like to pass content as part of the ForEach call
List<string> documents = GetAllDocuments();
documents.ForEach(CallAnotherFunction <<pass content>>);
List<string> templates = GetAllTemplates();
templates.ForEach(CallAnotherFunction <<pass another content>>);
是否有一种无需定义不同功能或使用迭代器即可实现的方法?
Is there a way I can achieve this without having to define different functions, or use iterators?
推荐答案
使用lambda表达式代替方法组:
Use lambda expressions instead of method groups:
List<string> documents = GetAllDocuments();
documents.ForEach( d => CallAnotherFunction(d, "some content") );
List<string> templates = GetAllTemplates();
templates.ForEach( t => CallAnotherFunction(t, "other content") );
这篇关于列出Foreach参数化的委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!