处置对象 [英] Disposed object

查看:77
本文介绍了处置对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两种形式(Form1,Form2)
在表格1中,我有一个按钮

Suppose I have two forms(Form1,Form2)
in form 1 I have a button

namespace sample_form
{
    public partial class Form1 : Form
    {
        Form2 f = new Form2();
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            f.Show();
        }
    }
}


在表格2中,我有一个文本框;

我想显示/关闭button1_click中的form2(在form1中)
它说对象已处置!,为此我在form2中写了


in form 2 I have a textbox;

I want to show/close form2 in button1_click(in form1)
it says object disposed !,for this in form2 I wrote

private void Form2_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            this.Hide();
        }




但是如果用户打开form2并在文本框中写东西然后关闭它,然后通过按钮打开form2,那么他写的文本仍保留在文本框中(因为我只是将其隐藏了),如何从Form2实例化一个新文本而不会出现错误:处置?! :((




but if user open the form2 and write somthing in textbox and close it,then open form2 by the button , the text he wrote remains in textbox (because I just hide it),how can I instance a new one from Form2 without the error:disposed ?! :((

推荐答案

为什么要隐藏它?为什么呢?
只需创建表单的新实例即可.

Why do u hide it? What for?
Just create new instance of your form.

private void button1_Click(object sender, EventArgs e)
{
    f = new Form2();
    f.Show();
}



另外,据我了解,垃圾收集器将在一段时间内处理您的表单,而f.Show将抛出异常.因此,每次都创建一个实例.



Also, as I understand, the garbage collector will dispose your form in some time, and f.Show will throw an exception. So, create instance every time.


如果您绝对需要重用同一表单实例,请编写一个Clear方法,将UI恢复为默认状态,然后再显示它. />
或者,如果不是必需的,则每次您想要显示它时都实例化一个新的表单实例(如上面的neosRu建议).
If you absolutely need to reuse the same form instance, then write a Clear method that restores the UI to the default state before re-showing it.

Or if that''s not a requirement, instantiate a new form instance each time you want to show it (as neosRu suggested above).


private void Form2_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            this.Hide();
        }



这段代码似乎是在form2中,而不是在form 1中.这是在创建错误.您需要将此代码放置在form1中,然后从此处将form2设置为null.



This code appears to be in form2 rather than form 1. This is creating the error. You need to place this code in form1 and set form2 to null from there.


这篇关于处置对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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