【问题标题】:StackOverflowException on recursive anonymous functions递归匿名函数上的 StackOverflowException
【发布时间】:2013-07-11 10:17:22
【问题描述】:

我正在尝试编写一个函数来检查字符串是否为回文,并使用this example,我正在尝试使用递归匿名函数来反转字符串:

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));
}

但每次我运行它都会得到一个StackOverflowException。我不清楚为什么,有什么想法吗?

【问题讨论】:

    标签: c# recursion anonymous-function stack-overflow


    【解决方案1】:

    这就是问题所在:

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

    除了奇怪的支撑样式之外,这只是用原始字符串递归 - 所以它会一直持续下去。我怀疑你打算在某处使用Substring,以便它使用更短的字符串进行递归......

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

    static string Reverse(string input)
    

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

    【讨论】:

    • 多么尴尬。应该一直是return revStr(s.Substring(1)) + s[0]
    • 刚刚试了一下。实际上,使用命名函数比使用匿名函数执行得更好
    • +1。当你完成修复代码时,让它正确地匿名递归:Anonymous Recursion in C#
    猜你喜欢
    • 2022-06-20
    • 2023-03-10
    • 2015-11-21
    • 2011-01-29
    • 2011-04-22
    • 2020-09-24
    • 1970-01-01
    • 2011-07-17
    • 2011-10-24
    相关资源
    最近更新 更多