C#构造函数时关闭表单 [英] C# Closing a form during a constructor

查看:140
本文介绍了C#构造函数时关闭表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有可能,而构造函数执行(或者干脆停止它显示在这个阶段)?

Is it possible to close a form while the constructor is executing (or simply to stop it showing at this stage)?

我有以下的code:

public partial class MyForm : Form
{        
    public MyForm()
    {
        if (MyFunc())
        {
            this.Close();
        }
    }
}

会抛出主(一个的ObjectDisposedException),在这里:

Which throws an ObjectDisposedException in Main(), here:

    static void Main()
    {            
        ...

        // Following line errors
        Application.Run(new MyForm());
    }

我试过检查MyForm的像这样的结果:

I’ve tried checking the result of MyForm like this:

static void Main()
{            
    ...

    MyForm frm = new MyForm();
    if (frm != null)
    {
        // Following line errors
        Application.Run(frm);
    }
}

但是,这似乎并没有帮助。谁能告诉我解决的办法吗?也许一个方法来检查的形式,看它是否仍然存在?

But that doesn’t seem to help. Can anyone tell me a way around this, please? Maybe a way to check the form to see if it still exists?

推荐答案

您可以做到这一点设置一个标志,关闭它在构造函数中,然后关闭它唯一的所示事件。当然,如果你这样做,是很有意义的移动code,以确定它是否应该被摆在首位有关闭。

The only thing you could do it set a flag to close it in the constructor, and then closing it in the Shown event. Of course, if you're doing that, it makes sense to move the code to determine whether it should be closed there in the first place.

这篇关于C#构造函数时关闭表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆