如何在c#中拥有一个包含子函数的函数

本文关键字:包含 子函数 函数 有一个 拥有 | 更新日期: 2023-09-27 17:52:35

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

我想要完成的例子

static void Main(string[] args)
{
  int x = 0
  subfunction bob()
  {
    x += 2;
  }
  bob();
  x += 1;
  bob();
  // x would equal 5 here
}

如何在c#中拥有一个包含子函数的函数

Use Action:

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

      act();
      x += 1;
      act();
      // x would equal 5 here
      Console.WriteLine(x);
}

你可以把你的参数包装成一个类。

public class MyParams
{
    public int X { get; set; }
}
public static void bob(MyParams p)
{
    p.X += 2;
}
static void Main()
{
    MyParams p = new MyParams { X = 0 };
    bob(p);
    p.X += 1;
    bob(p);
    Console.WriteLine(p.X);
}

这大致就是lambda答案在幕后所做的工作。

可以使用lambda表达式:

public static void SomeMethod () {
    int x = 0;
    Action bob = () => {x += 2;};
    bob();
    x += 1;
    bob();
    Console.WriteLine(x); //print (will be 5)
}

lambda表达式是以下部分() => {x += 2;}()表示该动作完全不需要输入。在嘉奖之间,您可以指定应该执行的语句。未在lambda表达式左侧定义的变量(如x)是有界的,就像C/c++/Java语言家族中正常的作用域规则一样。这里x因此与SomeMethod中的局部变量x结合。

Action是一个delegate,它指的是一个"方法",你可以把它称为一个高阶方法。

注意你的代码不是c#。

不能写int main作为main方法。

演示(Mono的c#交互shell csharp)

$ csharp
Mono C# Shell, type "help;" for help
Enter statements below.
csharp> public static class Foo {
      >  
      > public static void SomeMethod () {
      >         int x = 0;
      >         Action bob = () => {x += 2;};
      >         bob();
      >         x += 1;
      >         bob();
      >         Console.WriteLine(x);
      >     }
      >  
      > }
csharp> Foo.SomeMethod();
5