Can an anonymous method in C# call itself?

前端 未结 6 1889
-上瘾入骨i
-上瘾入骨i 2020-12-08 02:03

I have the following code:

class myClass
{
private delegate string myDelegate(Object bj);

protected void method()
   {
   myDelegate build = delegate(Object         


        
6条回答
  •  悲哀的现实
    2020-12-08 02:35

    If you use Y, your function becomes a parameter to the function itself, so that you can call it recursively:

    class myClass {
      private delegate string myDelegate(Object bj);
      protected void method() {
        myDelegate build = delegate(Object obj) {
          // f is the function itself, which is passed into the function
          return Functional.Y(f => bj => { 
            var letters = string.Empty;
            if (someCondition)
              return f(some_obj); // use f
            else return string.Empty;
    
          })(obj);
        };
      }
    }
    
    public static class Functional {
      public delegate Func Recursive(Recursive r);
      public static Func Y(Func, Func> f) {
        Recursive rec = r => a => f(r(r))(a);
        return rec(rec);
      }
    }
    

提交回复
热议问题