Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/264.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 递归匿名函数上的StackOverflowException_C#_Recursion_Anonymous Function_Stack Overflow - Fatal编程技术网

C# 递归匿名函数上的StackOverflowException

C# 递归匿名函数上的StackOverflowException,c#,recursion,anonymous-function,stack-overflow,C#,Recursion,Anonymous Function,Stack Overflow,我试图编写一个函数来检查字符串是否为回文,并使用,我试图使用递归匿名函数来反转字符串: static Boolean checkPalindromeAnonRec(string str) { str = str.ToLower().Replace(" ", String.Empty); Func<string, string> revStr = null; revStr = delegate(string s) { if (s.

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

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));
}
static Boolean checkPalindromeAnonRec(string str)
{
str=str.ToLower().Replace(“,String.Empty”);
Func revStr=null;
revStr=委托(字符串s)
{ 
如果(s.长度>1)
{return revStr(s)+s[0];}
其他的
{返回s;}
};
返回(str==revStr(str));
}

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

这就是问题所在:

if (s.Length > 1) 
  { return revStr(s) + s[0]; } 
除了奇怪的支撑样式之外,它只是与原始字符串一起递归-因此它将永远保持下去。我怀疑您打算在某个地方使用
子字符串
,以便使用较短的字符串进行递归

实际上,我会尝试将其作为一个简单的非匿名(但仍然是递归)方法来编写-因此,请确定如何递归编写:

static string Reverse(string input)

。。。然后,如果您仍然希望将其内联到
CheckPalindrome
方法中,您可以这样做。

这就是问题所在:

if (s.Length > 1) 
  { return revStr(s) + s[0]; } 
除了奇怪的支撑样式之外,它只是与原始字符串一起递归-因此它将永远保持下去。我怀疑您打算在某个地方使用
子字符串
,以便使用较短的字符串进行递归

实际上,我会尝试将其作为一个简单的非匿名(但仍然是递归)方法来编写-因此,请确定如何递归编写:

static string Reverse(string input)

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

多么尴尬。应该一直都是
return revStr(s.Substring(1))+s[0]
。刚刚尝试过。实际上,使用命名函数比使用匿名函数+1执行得更好。当你修复完代码后,让它成为正确的匿名递归:多么尴尬。应该一直都是
return revStr(s.Substring(1))+s[0]
。刚刚尝试过。实际上,使用命名函数比使用匿名函数+1执行得更好。当您完成修复代码时,请正确地使用匿名递归: