简体   繁体   English

C#将一个Action <>传递给另一个Action <>

[英]C# passing an Action<> into another Action<>

I am new to delegates and I am trying to pass an Action<> as a parameter of another Action<>. 我是代表的新手,我正在尝试将Action <>作为另一个Action <>的参数传递。 For example, (with code re-usability in mind) I was attempting to make a loop action and pass other actions into it to reduce the number of loops in my code: 例如,(考虑到代码的可重用性)我尝试进行循环操作并将其他操作传递到其中,以减少代码中的循环次数:

Action<int, Action<Control, Control>> loop = (int stop, Action<Control, Control> action) =>
{
    for (int i = 0; i < stop; i++)
    {
        for (int j = 0; j < stop; j++)
        {
            <action> pass Add;
        }
    }
};

Action<Control, Control> Add = (Control Parent, Control Child) => Parent.Controls.Add(Child);

The main objective is to be able to re-use the double for loop in such a way where I can mix and match the action inside of it with other actions. 主要目标是能够以这种方式重复使用double for循环,以便我可以将其内部的动作与其他动作进行混合和匹配。

Action<int, Action<Control, Control>> loop = (int stop, Action<Control, Control> action) =>
{
    for (int i = 0; i < stop; i++)
    {
        for (int j = 0; j < stop; j++)
        {
            //// invoke action with real arguments
            // action(controlParent, controlChild);
        }
    }
};

Action<Control, Control> Add = (Control Parent, Control Child) => Parent.Controls.Add(Child);

loop(1, Add);

如果要在主动作中使用另一个动作来循环,您的动作用法也不错。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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