[英]C# - declare method in argument (delegate)
In the code below I pass method B as an action to be perfomed on on the objects in the IterateObjects method. 在下面的代码中,我将方法B作为要在IterateObjects方法中的对象上执行的操作传递。 I would like to ask whether I can explicitly declare the method in the argument instead of passing it by name, something like this: 我想问一下我是否可以在参数中显式声明方法,而不是按名称传递它,如下所示:
a.IterateObjects(delegate void(string s){//method body})
Its not correct but I am sure I have seen something like that working. a.IterateObjects(delegate void(string s){//method body})
它不正确,但我确信我已经看到了类似的工作。 Could you please advise? 您能否提一些建议? Thank you 谢谢
DelTest a = new DelTest(); //class with method IterateObjects
a.IterateObjects(B) //HERE
private void B(string a)
{
listBox1.Items.Add(a);
}
//another class ....
public void IterateObjects(Action<string> akce)
{
foreach(string a in list)
{
akce(a);
}
}
是的你可以像这样使用lambda :
a.IterateObjects ( x => listBox1.Items.Add(x) );
delegate void MyFunctionDelegate(string a);
public void Main()
{
iterateObjects (delegate(string a){/*do something*/});
}
public void IterateObjects(MyFunctionDelegate akce)
{
foreach(string a in list)
{
akce(a);
}
}
http://msdn.microsoft.com/en-us/library/900fyy8e%28VS.80%29.aspx http://msdn.microsoft.com/en-us/library/900fyy8e%28VS.80%29.aspx
that's it :) 而已 :)
您可以通过lambda表达式在调用时将函数B声明为匿名函数。
您可以使用lambda表达式:
a.IterateObjects((string s) => listBox1.Items.Add(s))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.