简体   繁体   中英

StackOverflowException on recursive anonymous functions

I'm trying to write a function to check whether a string is a palindrome, and using this example , I'm trying to reverse the string using a recursive anonymous function:

static Boolean checkPalindromeAnonRec(string str)
{
    str = str.ToLower().Replace(" ", String.Empty);
    Func<string, string> revStr = null;
    revStr = delegate(string s) 
      { 
        if (s.Length > 1) 
          { return revStr(s) + s[0]; } 
        else 
        { return s; } 
      };

    return (str == revStr(str));
}

But every time I run it I get a StackOverflowException . It's not obvious to me why, any ideas?

Well this is the problem:

if (s.Length > 1) 
  { return revStr(s) + s[0]; } 

Aside from the odd bracing style, that's just recursing with the original string - so it will keep going forever. I suspect you meant to use Substring somewhere so that it recursed using a shorter string...

I would actually try writing it as a simple non-anonymous (but still recursive) method to start with - so work out how you would recursively write:

static string Reverse(string input)

... then if you still want to inline that into your CheckPalindrome method, you can do so.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM