如何在C#中包含一个包含子函数的函数

Che*_*her 2 c# function

我有一部分代码在函数中重复多次.但是我想要它的功能,但我想知道我的函数的变量,所以它可以修改它们而不需要传递它们(因为有很多).

我想要完成的例子

static void Main(string[] args)
{
  int x = 0

  subfunction bob()
  {
    x += 2;
  }

  bob();
  x += 1;
  bob();
  // x would equal 5 here
}
Run Code Online (Sandbox Code Playgroud)

vmg*_*vmg 7

使用行动:

static void Main(string[] args)
{
      int x = 0;
      Action act = ()=> {
        x +=2;
      };


      act();
      x += 1;
      act();
      // x would equal 5 here
      Console.WriteLine(x);
}
Run Code Online (Sandbox Code Playgroud)