Windows Forms项目对象互实例化引发System.StackOverflowException
System.StackOverflowException 错误原因及修复方案
你遇到的错误完全是循环实例化导致的:
- 创建
Form1实例时,会自动初始化字段temelislemlerobjesi = new TemelIslemler() - 而
TemelIslemler类的字段又会创建新的Form1 frm1nesnesi = new Form1() - 这个过程无限重复,直到调用栈被耗尽,触发
System.StackOverflowException
另外这种写法还有逻辑问题:TemelIslemler里新建的Form1是全新的后台窗体实例,不是用户正在操作的界面,就算没报错,调用方法时也不会影响可见的窗体。
修复步骤:
1. 修改TemelIslemler类,通过构造函数接收Form1实例
去掉类内部的Form1实例化,改为从外部传入当前操作的窗体对象:
using System; using System.Diagnostics; namespace MitroT { internal class TemelIslemler { public string sonuc; private readonly Form1 _currentForm; // 构造函数接收Form1实例 public TemelIslemler(Form1 formInstance) { _currentForm = formInstance; } public void labelduzeni() { switch (sonuc) { case "Posta": _currentForm.label1.Visible = true; _currentForm.label1.Text = "Posta uygulamasını açıyorum"; Process.Start("outlookmail://"); break; } } public void yuklenmeac() { _currentForm.metroProgressSpinner1.Visible = true; _currentForm.label8.Visible = true; } public void yuklenmekapat() { _currentForm.metroProgressSpinner1.Visible = false; _currentForm.label8.Visible = false; } } }
2. 修改Form1类,实例化时传入当前窗体
把字段初始化移到构造函数里,传入this(当前Form1实例):
using MetroFramework.Animation; using System; using System.Windows.Forms; using Transitions; namespace MitroT { public partial class Form1 : Form { public Form1() { InitializeComponent(); // 传入当前Form1实例给TemelIslemler temelislemlerobjesi = new TemelIslemler(this); } TemelIslemler temelislemlerobjesi; // 仅声明字段,不在此处初始化 bool ac = false; private void Form1_Load(object sender, EventArgs e) { } private void metroTextBox1_Click(object sender, EventArgs e) { metroTabControl1.SelectedTab = metroTabPage4; } private void metroTextBox2_Click(object sender, EventArgs e) { } private void metroButton1_Click(object sender, EventArgs e) { temelislemlerobjesi.yuklenmeac(); // 修正判断逻辑:用||代替&&,或直接用string.IsNullOrWhiteSpace更简洁 if(string.IsNullOrWhiteSpace(textBox1.Text) || textBox1.Text == " ") { MessageBox.Show("İleti boş ve/veya algılanamaz.", "LokumT", MessageBoxButtons.OK, MessageBoxIcon.Information); temelislemlerobjesi.yuklenmekapat(); } else { string girdi = textBox1.Text; string girdiduzenli = girdi.Replace(",", " "); string[] girdidizisi = girdiduzenli.Split(' '); foreach(string g in girdidizisi) { //2.aşama if(ac) { if(g=="Posta") { temelislemlerobjesi.sonuc = g; // 调用方法触发界面更新 temelislemlerobjesi.labelduzeni(); } } //1.aşama if(g=="aç") { ac = true; } } } } } }
额外优化提示:
- 原代码中
textBox1.Text== " " && textBox1.Text==null && textBox1.Text==string.Empty判断逻辑错误,三个条件不可能同时成立,改成||或者直接用string.IsNullOrWhiteSpace(textBox1.Text)(自动判断null、空字符串和全空白) - 设置
sonuc = "Posta"后,需要手动调用labelduzeni()才能触发界面更新,代码中已补上这一步
内容的提问来源于stack exchange,提问作者salihon
相关产品推荐
相关产品推荐

