递归匿名函数的StackOverflowException

Jel*_*lla 1 c# stack-overflow recursion 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));
}
Run Code Online (Sandbox Code Playgroud)

但是每次我跑它都会得到一个StackOverflowException.对我来说,为什么,任何想法都不明显?

Jon*_*eet 5

这是问题所在:

if (s.Length > 1) 
  { return revStr(s) + s[0]; } 
Run Code Online (Sandbox Code Playgroud)

除了奇怪的支撑风格,它只是与原始字符串一起递归- 所以它将永远持续下去.我怀疑你打算在Substring某处使用,以便使用较短的字符串进行递归...

我实际上会尝试将其编写为一个简单的非匿名(但仍然是递归)方法来开始 - 所以弄清楚如何递归写:

static string Reverse(string input)
Run Code Online (Sandbox Code Playgroud)

...然后,如果您仍想将其内联到您的CheckPalindrome方法中,您可以这样做.