[英]Error 'System.StackOverflowException' in mscorlib.dll
How to solve this error? 如何解决这个错误?
This is my code 这是我的代码
public void X()
{
foreach (char c in txtNumbers.Text)
{
sum = sum + (int.Parse(c.ToString()) * int.Parse(c.ToString()));
}
txtNumbers.Text = (sum.ToString());
sum = 0;
if (txtNumbers.Text == "1")
{
Response.Write("happy numbers");
return;
} else {
X();
}
}
And this is the error... 这是错误...
if the numbers don't add up to "1", your program is going to enter into an infinite loop. 如果数字加起来不等于“ 1”,则您的程序将进入无限循环。 and crash.
和崩溃。 hard.
硬。 like it did.
喜欢它。
This is because in your else
block, you call X()
method again. 这是因为在您的
else
块中,您再次调用X()
方法。 And there seems to be no way to stop your recursion and hence your program is crashing. 而且似乎没有办法停止递归,因此您的程序崩溃了。
A simple fix: 一个简单的解决方法:
public void X()
{
foreach (char c in txtNumbers.Text)
{
sum = sum + (int.Parse(c.ToString()) * int.Parse(c.ToString()));
}
txtNumbers.Text = (sum.ToString());
sum = 0;
if (txtNumbers.Text == "1")
{
Response.Write("happy numbers");
return;
}else{
Response.Write("sad numbers");
}
}
Also, I recommend using TryParse()
methods, but that's for another season. 另外,我建议使用
TryParse()
方法,但这是另一个季节。
I believe the error is that the X
method recursively calls itself. 我相信错误是
X
方法递归调用了它自己。 This is the root cause of the stack overflow but it is actually getting triggered on the int.Parse
call. 这是堆栈溢出的根本原因,但实际上是在
int.Parse
调用上触发的。 You need to change your else logic so that it doesn't keep branching into X()
without ever terminating 您需要更改else逻辑,以便在不终止的情况下不会继续分支到
X()
If txtNumbers.Text
is never "1"
you will have a recursion that continues until you get the StackOverflowException. 如果
txtNumbers.Text
绝不为"1"
,则将具有递归,直到获得StackOverflowException为止。 Simply because you invoke X()
when txtNumbers.Text
is different from "1"
. 仅仅因为当
txtNumbers.Text
与"1"
不同时调用X()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.