Dispose close null showdialog

本文探讨了Dispose与Close方法的区别,并通过实例演示了如何正确使用这两种方法。Dispose方法用于释放资源,而Close方法通常用于关闭连接。文章强调了在Singleton模式中使用Close方法的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    at first ,i  have a reference the others' article:

 这就是Dispose和null之间的区别。Dispose和Close是相同的,据说是因为有些类有Open的方法,所以为了对应才搞出了一个Close方法。Dispose()方法实际上是销毁了对象的实例,但是该对象变量仍然指向这块被销毁的内存地址上!而只要有所指向,它就绝不等于null!而若原来夫frm = new Form1();然后又frm = null;这意味着frm不再指向new出来的对象,他们之间的关系被“切断”了,frm成了一个没有指向的变量,但同时new出来的那个对象也占据着一块内存,它并没有被干掉!后来我又发现,窗体在执行Close()方法后会激发Closing事件,而使用dispose()方法则不会激发该事件。在singleton模式中,单例窗体的Closing事件里面,加入了“frm=null;”这么一句话,所以不要用dispose()关闭单例窗体,而要用Close()方法关闭。引申出来,所有拥有Close()方法的类,最好都用Close()方法关闭,而不要用Dispose()方法。
所以,上面的例子中,把frm1关掉后,它new出来的那个对象所占用的地址被dispose掉了,但是变量frm1仍然指向这块被dispose掉的地址!所以它也就不等于null!所以当再次单击Button1的时候,直接进入了else部分,导致了错误。那怎么解决呢?这么办,在Form1的Closed事件中将frm1设置成null,就可以了。因为关闭窗体,执行dispose的时候,窗体内的其他代码并不停止,直到执行完毕,所以,可以将frm1设置成null,完全没有问题。
这里还有另外一个问题。假如一个对象(自定义的类的实例)没有dispose掉,就把它设置成null,那这块内存怎么办呢?垃圾回收机制会自动收拾它的。但是垃圾回收机制,不能保证何时去回收它,所以你也不知道它到底啥时候能回收掉,这样可能影响系统的效率。解决方法是,使该类继承IDisposable接口,然后实现他的Dispose()方法。函数内写GC.SuppressFinalize(this);这样,如果手动调用dispose()方法,GC就不会通过析构函数再次销毁对象了。尤其当这个对象作为局部变量的时候,这样做是很有必要的。可以将dispose()写入finally{}语句中,更好的方法是使用using关键字把代码装入{}中。例如:
Using(Class1 cls1 = new Class())
{。。。。}
Using里的参数必须是实现了dispose方法的对象。当程序运行出{}时,自动销毁cls1(但是cls1!=null,这个已经反复说过多次了)。真正是实现的时候,可能还要考虑到多线程等诸多问题。

         now ,i do a test myself

namespace TestFrmDispose
{
    public partial class MainFrm : Form
    {
        public MainFrm()
        {
            InitializeComponent();
        }
        SubWindow myWindow;
        private void MainFrm_Load(object sender, EventArgs e)
        {
            myWindow = new SubWindow();
            if (myWindow.ShowDialog(this) == DialogResult.OK)
            {
              
            }
            else
            {
           
            }
        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            if (myWindow == null)
            {
                this.richTextBox1.AppendText("receive DialogResult and the window is Closed");
            }
            else
            {
                this.richTextBox1.AppendText("receive DialogResult and the window has exists");
                myWindow.Visible = true;//this word is used to test whether the window is hited;//the key is right;
                myWindow.Text = "123";
            }
        }

    }
}

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace TestFrmDispose
{
    public partial class SubWindow : Form
    {
        public SubWindow()
        {
            InitializeComponent();
        }

        private void btnSure_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.OK;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
        }
    }
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace TestFrmDispose
{
    public partial class SubWindow : Form
    {
        public SubWindow()
        {
            InitializeComponent();
        }

        private void btnSure_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.OK;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
        }
    }
}

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace _2 { public partial class FormMannage : Form { public FormMannage() { InitializeComponent(); } private SqlConnection _connection; // 声明 SqlConnection 对象 //知识点信息 修改功能 public static int Pid; public static string Pname; public static string Stype; public static string Savedate; public static string Content; public static string Image; public static byte[] ImageData; // 存储图片的二进制数据 private void LoadPoint() { dgv.Rows.Clear(); Dao2 dao = new Dao2(); dao.Connect(); string sql = "SELECT * FROM T_Point"; // 修复:使用 using 语句确保 SqlDataReader 被正确释放 using (SqlDataReader reader = dao.Read(sql)) // 假设 dao.Read 返回 SqlDataReader { while (reader.Read()) { dgv.Rows.Add( reader[0].ToString(), reader[1].ToString(), reader[2].ToString(), reader[3].ToString(), reader[4].ToString(), reader[5].ToString() ); } } // 此处 reader 会自动调用 Dispose() 释放资源 dao.Close(); // 关闭数据库连接 } //刷新数据 private void button4_Click(object sender, EventArgs e) { LoadPoint(); } private void lbName_Click(object sender, EventArgs e) { } private void txtKey_TextChanged(object sender, EventArgs e) { } //进行关键字搜索查询 private void btnSearch_Click(object sender, EventArgs e) { //拿到关键字 string key = txtKey.Text.Trim(); //以关键字进行模糊查询 Dao2 dao = new Dao2(); dao.Connect(); string sql = $"select * from T_Point where Pname like '%{key}%'or Stype like '%{key}%'"; SqlDataReader reader = dao.Read(sql); //清空表格 dgv.Rows.Clear(); //结果显示到表格控件中 while (reader.Read()) { dgv.Rows.Add(reader[0].ToString(), reader[1].ToString(), reader[2].ToString(), reader[3].ToString(), reader[4].ToString(),reader[5].ToString()); } reader.Close(); dao.Close(); } //删除知识点 private void button3_Click(object sender, EventArgs e) { //获取到当前选中的知识点编号 key if (lbid.Text == "NULL") { MessageBox.Show("未选中知识点", "消息", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } //删除对应的数据 Dao2 dao = new Dao2(); dao.Connect(); string sql = $"delete T_Point where Pid='{int.Parse(lbid.Text)}'"; if (dao.Execute(sql) > 0) { //删除成功 //两个对应的lb数据的修改 null lbid.Text = "NULL"; lbName.Text = "NULL"; //更新表格数据 LoadPoint(); dao.Close(); MessageBox.Show("删除成功", "消息", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { dao.Close(); MessageBox.Show("删除失败", "消息", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } //查看简介 private void button5_Click(object sender, EventArgs e) { if (lbName.Text == "NULL") { MessageBox.Show("未选中知识点!", "消息", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } // 确保 lbid 是正确的知识点编号 if (string.IsNullOrEmpty(lbid.Text) || lbid.Text == "NULL") { MessageBox.Show("知识点编号无效!", "消息", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } // 获取知识点的编号 int pointId; if (!int.TryParse(lbid.Text, out pointId)) { MessageBox.Show("知识点编号格式错误!", "消息", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } Dao2 dao = new Dao2(); dao.Connect(); try { string sql = "SELECT [Content] FROM T_Point WHERE Pid = @Pid"; // 使用dao.Connection替代未定义的_connection using (SqlCommand cmd = new SqlCommand(sql, dao.Connection)) // 关键修改点 { cmd.Parameters.AddWithValue("@Pid", pointId); object result = cmd.ExecuteScalar(); if (result != null) { string introduce = result.ToString(); MessageBox.Show(introduce, $"{lbName.Text}的简介", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("未找到该知识点的简介!", "消息", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } } catch (SqlException ex) { MessageBox.Show($"获取简介时发生错误:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { dao.Close(); } } //选中数据 private void dgv_CellContentClick(object sender, DataGridViewCellEventArgs e) { if (dgv.CurrentRow == null || dgv.CurrentRow.Cells[0].Value == null) { MessageBox.Show("选中无效数据!", "消息", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } string Pid = dgv.CurrentRow.Cells[0].Value.ToString();//当前选中的知识点编号 string Pname = dgv.CurrentRow.Cells[1].Value.ToString();//当前选中的知识点名称 lbid.Text = Pid; lbName.Text =Pname; FormMannage.Pid = int.Parse(Pid); // 将字符串转换为整数并赋值给 FormMannage.Pid FormMannage.Pname = Pname; FormMannage.Stype = dgv.CurrentRow.Cells[2].Value.ToString(); FormMannage.Savedate = dgv.CurrentRow.Cells[3].Value.ToString(); FormMannage.Content = dgv.CurrentRow.Cells[4].Value.ToString(); } //修改知识点 private void button2_Click(object sender, EventArgs e) { // 确保有选中的知识点 if (lbid.Text == "NULL") { MessageBox.Show("未选中知识点!", "消息", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } // 将选中的知识点数据传递给更新窗体 FormUpdatePoint form = new FormUpdatePoint(); form.Pid = Pid; form.Pname = Pname; form.Stype = Stype; form.Savedate = Savedate; form.Content = Content; form.ImageData = ImageData; form.ShowDialog(); } private void FormMannage_Load(object sender, EventArgs e) { } } } 如何实现在搜索之前就能选中数据
07-04
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值