有两种形式,一类。从主窗体我打开第二个:
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
this.Hide();
form2.ShowDialog();
this.Close();
}
在另一个类中,我还为第二种形式创建了一个对象
Form2 form2 = new Form2();
并且在这一行上它会抛出一个异常 System.StackOverflowException。我没有在第二个表单上创建对象。你怎么能解决这个问题?毕竟我需要通过这个类的方法来改变第二个窗体上的组件。这是整个代码:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
this.Hide();
form2.ShowDialog();
this.Close();
}
}
public partial class Form2 : Form
{
Ans ans = new Ans();
private int index = -1;
public Form2()
{
InitializeComponent();
ans.Test(radioButton1, radioButton2);
Shown += Form1_Shown15;
}
private void radioButton_Click(object sender, EventArgs e)
{
RadioButton button = sender as RadioButton;
if (button == radioButton1) { index = 0; }
if (button == radioButton2) { index = 1; }
}
private async void Form1_Shown25(object sender, EventArgs e)
{
verticalProgressBar1.Value = 100;
for (int i = 25 * 60; i > 0; i--)
{
verticalProgressBar1.Value = i * 100 / (25 * 60);
await Task.Delay(1000);
}
Close();
}
private void button3_Click(object sender, EventArgs e)
{
try
{
ans.Correct(index);
radioButton1.Checked = false;
radioButton2.Checked = false;
index = -1;
}
catch { return; }
ans.Index++;
if (ans.Index > 47)
{
MessageBox.Show();
return;
}
ans.Test(radioButton1, radioButton2);
}
}
public class Ans
{
Form2 form2 = new Form2();
private List<string> test = new List<string>()
{ };
private bool[,] boolTest =
{ };
public int correct = 0;
public int TestIndex { get; set; }
public int Index { get; set; }
public string GetCorrect { get; set; }
public void Test(Control control1, Control control2)
{
control1.Text = test[TestIndex];
TestIndex++;
control2.Text = test[TestIndex];
TestIndex++;
}
public void Correct(int i)
{
SystemSounds.Exclamation.Play();
#region 1-10
//1
if (Index == 0)
{
if (boolTest[0, i] == true)
{
form2.pictureBox2.BackColor = Color.Green;
form2.label2.Text = "";
correct++;
return;
}
else
{
form2.pictureBox2.BackColor = Color.Red;
form2.label2.BackColor = Color.Red;
}
}
}
}
Form2一切都很简单,创建时当创建类时
Ans,当它
Form2被创建时当创建类时
Ans,当它
Form2被创建时当创建类时
Ans,当它
Form2被创建时当创建类时
Ans,当它
Form2被创建时当创建类时
Ans,当它
Form2被创建时当创建类时
Ans,当它
Form2被创建时当创建类时
Ans,...等等
每个这样的调用都会将返回点压入堆栈。堆栈存储一个返回的位置,因为当您编写
return或方法结束时,处理器会从该堆栈中取出一个指针返回到哪里。你有一个调用中的调用,等等。所有这些都在堆栈上。但是堆栈有一个大小,通常是 1 兆字节。由于您一直在此处添加回溯点(无限递归),因此堆栈溢出并且您得到
StackOverflowException.无限递归的典型例子
你的情况看起来像这样
不要在类中创建新表单
Ans,使用现有表单。