我正在尝试编写一个函数来检查字符串是否为回文,并使用 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
。我不明白为什么,有什么想法吗?
最佳答案
这就是问题所在:
if (s.Length > 1)
{ return revStr(s) + s[0]; }
除了奇怪的支撑风格外,这只是 与原始字符串的递归 - 所以它将永远持续下去。我怀疑您打算在某处使用 Substring
以便它使用较短的字符串递归...
我实际上会尝试将它写成一个简单的非匿名(但仍然是递归的)方法来开始 - 所以弄清楚你将如何递归地写:
static string Reverse(string input)
...那么如果您仍想将其内联到您的 CheckPalindrome
方法中,您可以这样做。
关于c# - 递归匿名函数的 StackOverflowException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17622242/