This question already has answers here:
C#: Recursive functions with Lambdas
                                
                                    (4个答案)
                                
                        
                                6年前关闭。
            
                    
如何从自身调用Func函数?

例如:

 Func<int, int> f = x => {
      // do stuff
      if (x > 5) { return f(x); }
      // do other stuff
 };

最佳答案

dlev的答案很简单,但是您也可以这样做:

首先声明一个接受自身作为参数的委托类型:

public delegate TResult RecursiveFunc<TParam, TResult>(
    TParam param1,
    RecursiveFunc<TParam, TResult> func);


注意:当然,委托不必一定是通用的。

现在,您可以像这样创建lambda表达式:

RecursiveFunc<int, int> f = (x, g) => {
    // do stuff
    if (x > 5) { return g(x, g); }
    // do other stuff
};

f(123, f); // Invoke recursively

关于c# - 函数变量调用自身,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16368904/

10-11 06:35