以代码作为参数的函数

本文关键字:函数 参数 代码 | 更新日期: 2023-09-27 17:55:08

我有很多函数,但我确实需要在另一个函数中运行它们。

我知道我可以做这样的事情

public void Method1()
{
bla bla
}

public void Method2()
{
bla bla
}
public void Wrapper(Action<string> myMethod)
        {
        method{
            myMethod()
              }
            bla bla
         }

然后使用类似这样的东西来调用它们:

wrapper(Method1());

问题是有时我需要同时运行方法1和方法2。他们很多。有时一个,有时同时几个。

所以我认为做这样的事情会很棒:

Wrapper({bla bla bla; method(); bla bla; }
{
method{
bla bla bla;
 method();
 bla bla;
        }
}

在方法内部运行代码块,方法的参数就是代码块。您认为有可能还是会推荐另一种方法?

以代码作为参数的函数

public static void Wrapper(Action<string> myMethod)
{
    //...
}

您可以使用 lambda 表达式指定myMethod

static void Main(string[] args)
{
    Wrapper((s) =>
    {
        //actually whatever here
        int a;
        bool b;
        //..
        Method1();
        Method2();
        //and so on
    });
}

也就是说,您不需要显式定义具有所需签名的方法(此处匹配Action<string>),但您可以编写内联 lambda 表达式,做任何您需要的事情。

从 MSDN:

通过使用 lambda 表达式,您可以编写可以 作为参数传递或作为函数调用的值返回。

如果您已经有一些接受 Action 参数的方法,则可以使用匿名方法将一堆方法组合在一起以进行顺序执行。

//what you have
public void RunThatAction(Action TheAction)
{
  TheAction()
}
//how you call it
Action doManyThings = () =>
{
  DoThatThing();
  DoThatOtherThing();
}
RunThatAction(doManyThings);

如果您经常按顺序调用方法,请考虑创建一个接受尽可能多的操作的函数...

public void RunTheseActions(params Action[] TheActions)
{
  foreach(Action theAction in TheActions)
  {
    theAction();
  }
}
//called by
RunTheseActions(ThisAction, ThatAction, TheOtherAction);

你说了两次"同时",这让我想到了并行性。 如果要同时运行多个方法,可以使用任务来执行此操作。

public void RunTheseActionsInParallel(params Action[] TheActions)
{
  List<Task> myTasks = new List<Task>(TheActions.Count);
  foreach(Action theAction in TheActions)
  {
    Task newTask = Task.Run(theAction);
    myTasks.Add(newTask);
  }
  foreach(Task theTask in myTasks)
  {
    theTask.Wait();
  }
}