简体   繁体   English

递归匿名函数上的StackOverflowException

[英]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 . 但是每次运行它时,我都会得到一个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... 我怀疑您打算在某个地方使用Substring ,以便使用较短的字符串重复出现...

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. ...然后,如果您仍然想将其内联到CheckPalindrome方法中,则可以这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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