c# – 表单类中的stackoverflow异常

前端之家收集整理的这篇文章主要介绍了c# – 表单类中的stackoverflow异常前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当我尝试在表单类中创建表单类的对象时,它会在发生stackoverflow时给出异常.但是,当我在方法中声明表单类的对象时,它工作正常.代码如下:
  1. namespace WindowsFormsApplication6
  2. {
  3. public partial class Form1 : Form
  4. {
  5.  
  6. **Form1 f1 = new Form1();**//gives stackoverflow exception.......
  7.  
  8. char[] ar = new char[15];
  9. int flag = 0,end;
  10. double val1,val2,res;
  11. string oprt;
  12. public Form1()
  13. {
  14. InitializeComponent();
  15. }
  16.  
  17. private void masters(object sender,EventArgs e)
  18. {
  19. ar[i] = char.Parse(((Button)sender).Text);
  20. if (char.IsDigit(ar[i]))
  21. {
  22. if (flag != 0)
  23. {
  24. if (textBox1.Text == oprt)
  25. {
  26. textBox1.Clear();
  27. }
  28.  
  29. }
  30. else
  31. {
  32. if (end == 1)
  33. {
  34. textBox1.Clear();
  35. end = 0;
  36. }
  37. }
  38. Button ansBox = sender as Button;
  39. textBox1.Text += ansBox.Text;
  40.  
  41. }
  42. else if (char.IsSymbol(ar[i]))
  43. {
  44. if (textBox1.TextLength != 0)
  45. {
  46. val1 = double.Parse(textBox1.Text);
  47. textBox1.Clear();
  48. Button bt = sender as Button;
  49. if (bt != null)
  50. textBox1.Text = bt.Text;
  51. oprt = bt.Text;
  52. // dot.Enabled = true;
  53. flag = 1;
  54. }
  55. }
  56. }
  57.  
  58.  
  59.  
  60.  
  61.  
  62. private void button14_Click(object sender,EventArgs e)
  63. {
  64. if (textBox1.TextLength != 0)
  65. {
  66. val2 = double.Parse(textBox1.Text);
  67. switch (oprt)
  68. {
  69. case "+": res = val1 + val2;
  70. break;
  71. case "-": res = val1 - val2;
  72. break;
  73. case "*": res = val1 * val2;
  74. break;
  75. case "/": res = val1 / val2;
  76. break;
  77. }
  78.  
  79.  
  80. textBox1.Text = res.ToString();
  81. flag = 0;
  82. end = 1;
  83. }
  84. }
  85. }
  86. }
  87.  
  88. }

解决方法

创建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.

猜你在找的C#相关文章