当我尝试在表单类中创建表单类的对象时,它会在发生stackoverflow时给出异常.但是,当我在方法中声明表单类的对象时,它工作正常.代码如下:
- namespace WindowsFormsApplication6
- {
- public partial class Form1 : Form
- {
- **Form1 f1 = new Form1();**//gives stackoverflow exception.......
- char[] ar = new char[15];
- int flag = 0,end;
- double val1,val2,res;
- string oprt;
- public Form1()
- {
- InitializeComponent();
- }
- private void masters(object sender,EventArgs e)
- {
- ar[i] = char.Parse(((Button)sender).Text);
- if (char.IsDigit(ar[i]))
- {
- if (flag != 0)
- {
- if (textBox1.Text == oprt)
- {
- textBox1.Clear();
- }
- }
- else
- {
- if (end == 1)
- {
- textBox1.Clear();
- end = 0;
- }
- }
- Button ansBox = sender as Button;
- textBox1.Text += ansBox.Text;
- }
- else if (char.IsSymbol(ar[i]))
- {
- if (textBox1.TextLength != 0)
- {
- val1 = double.Parse(textBox1.Text);
- textBox1.Clear();
- Button bt = sender as Button;
- if (bt != null)
- textBox1.Text = bt.Text;
- oprt = bt.Text;
- // dot.Enabled = true;
- flag = 1;
- }
- }
- }
- private void button14_Click(object sender,EventArgs e)
- {
- if (textBox1.TextLength != 0)
- {
- val2 = double.Parse(textBox1.Text);
- switch (oprt)
- {
- case "+": res = val1 + val2;
- break;
- case "-": res = val1 - val2;
- break;
- case "*": res = val1 * val2;
- break;
- case "/": res = val1 / val2;
- break;
- }
- textBox1.Text = res.ToString();
- flag = 0;
- end = 1;
- }
- }
- }
- }
- }
解决方法
创建Form1的实例将导致f1属性使用Form1的实例进行初始化,这将导致使用Form1的实例初始化f1属性,这将导致要使用Form1实例初始化的f1属性,该实例将导致使用Form1实例初始化f1属性,这将导致使用Form1实例初始化f1属性,这将导致f1属性使用实例初始化Form1的一个实例将导致f1属性初始化,这将导致f1属性初始化为Form1的实例,这将导致f1属性要使用Form1的实例初始化,这将导致f1属性使用Form1的实例初始化,这将导致f1属性为使用Form1的实例进行初始化,这将… Stack Overflow!
在类中的方法中,’f1’将是本地的,并且仅在调用的生命周期中存在.除非您在实例化的Form1上调用相同的方法,否则不会创建后续的Form1.