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. 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. 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 Iterat开发者_开发问答eObjects(Action<string> akce)
{
foreach(string a in list)
{
akce(a);
}
}
Yes you can use a lambda like so :
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
that's it :)
You can declare function B as anonymous function at the point of calling, through a lambda expression.
You can use a lambda expression:
a.IterateObjects((string s) => listBox1.Items.Add(s))
精彩评论