【发布时间】:2021-05-14 13:10:03
【问题描述】:
好的,首先是 28x28 正方形的按钮。当我使用递归函数禁用所有没有文本的按钮(button.Name = string.Empty)时,例如当我单击图像中的 8x2 按钮时,递归函数会禁用从 8x2 到 8x8 的所有按钮在循环中一一向东。 (代码 1)
但是,当我向LoopControlEmpty 函数添加更多递归方式时,以不同的方式(如 N、NW、SE 等)禁用更多块。程序给了我一个 StackOverFlow 错误。 (代码 2)
我需要找到一种方法来用它们的名字调用按钮,而不是在 foreach 循环中打开所有 81 个按钮 但可能它会再次给我同样的错误,因为很多时间它会去递归。或者我需要找到另一种算法来禁用按钮。
按钮名称是这样的 => 对于 0x0 中的按钮 button.Name = "button0x0"
代码 1
private void btn_Click(object sender, EventArgs e)
{
// Using sender as Button because i need to reach that buttons properties.
Button btn = sender as Button;
if (btn.Text == "M")
{
btn.BackColor = Color.FromArgb(255, 0, 0);
foreach (Button button in this.Controls)
{
button.Enabled = false;
}
}
else if (btn.Text == string.Empty)
{
btn.Enabled = false;
LoopControlEmpty(btn);
}
else
btn.Enabled = false;
}
public void LoopControlEmpty(Button btn)
{
foreach (Button btnIn in this.Controls)
{
// Going East
if (btn.Location.X + 28 == btnIn.Location.X && btn.Location.Y == btnIn.Location.Y && btnIn.Text == string.Empty)
{
btnIn.Enabled = false;
LoopControlEmpty(btnIn);
continue;
}
}
return;
}
代码 2
public void LoopControlEmpty(Button btn)
{
foreach (Button btnIn in this.Controls)
{
// Going East
if (btn.Location.X + 28 == btnIn.Location.X && btn.Location.Y == btnIn.Location.Y && btnIn.Text == string.Empty)
{
btnIn.Enabled = false;
LoopControlEmpty(btnIn);
continue;
}
//Going North
if (btn.Location.X == btnIn.Location.X && btn.Location.Y + 28 == btnIn.Location.Y && btnIn.Text == string.Empty)
{
btnIn.Enabled = false;
LoopControlEmpty(btnIn);
continue;
}
//Goint South-West
if (btn.Location.X - 28 == btnIn.Location.X && btn.Location.Y -28 == btnIn.Location.Y && btnIn.Text == string.Empty)
{
btnIn.Enabled = false;
LoopControlEmpty(btnIn);
continue;
}
}
return;
}
【问题讨论】:
-
我很困惑你为什么要递归。你能不能只从这个函数返回当前的 Button 并继续传递它直到
Button.Text == "" -
现在是学习如何使用调试器单步调试代码并查看发生了什么的好时机。
-
@RufusL 不要成为 *ss 我知道那里发生了什么 :)
-
不,我是认真的。如果您单步执行代码,您应该能够看到堆栈溢出的原因。
-
@RufusL 它正在溢出,因为发生了大量递归,并且每次它都会打开 81 个按钮
标签: c# recursion stack-overflow