3

我正在尝试为列表的每个成员调用一个函数,但将其他参数传递给委托。

如果我有一个名为的列表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>>);

有没有一种方法可以实现这一点而无需定义不同的函数或使用迭代器?

4

2 回答 2

9

使用 lambda 表达式而不是方法组:

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

List<string> templates = GetAllTemplates();
templates.ForEach( t => CallAnotherFunction(t, "other content") );
于 2013-04-10T09:32:56.703 回答
1

使用 lambda 表达式:

string content = "Other parameter value";
documents.ForEach(x => CallAnotherFunction(x, content));
于 2013-04-10T09:32:20.633 回答