简体   繁体   中英

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 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

that's it :)

您可以通过lambda表达式在调用时将函数B声明为匿名函数。

您可以使用lambda表达式:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM