C # - declare a method in an argument (delegate)

In the code below, I pass method B as the action to be performed on objects in the IterateObjects method. I would like to ask if I can explicitly declare a method in an argument, and not pass it by name, something like this: a.IterateObjects(delegate void(string s){//method body}) This is not correct, but I'm sure that saw something like that. Could you please advise? Thanks 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); } } 
+4
source share
4 answers
  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

what he:)

+1
source

Yes, you can use lambda like this:

 a.IterateObjects ( x => listBox1.Items.Add(x) ); 
+3
source

You can declare function B as an anonymous function at the point of call through lambda expression .

0
source

You can use lambda expression:

 a.IterateObjects((string s) => listBox1.Items.Add(s)) 
0
source

Source: https://habr.com/ru/post/1303774/


All Articles