流浪のwolf

卷帝

导航

析构方法和垃圾回收器

// 垃圾回收机制:
// 回收非托管资源 -- Windows窗口句柄 ,数据库的链接,GDI对象,独占文件锁等等对象

// 1.Dispose() 需要实现 IDisposable 接口
// 2.Close()和 Dispose()的区别 -- Close关闭对象,没有完全释放(可以再次使用)。Dispose完全释放(再次使用重新创建)。

// 析构方法
//     用处:释放对象
//     谁在使用:GC垃圾回收器在调用

测试类

Close方法和Dispose方法的区别?

try{}catch{}finally{} 和 useing(){}的关系  ---   语法糖的关系。

class testCtor {
    public testCtor()
    {
        Console.WriteLine("第二个构造函数");
    }
    public testCtor(int a)
    {
        Console.WriteLine("第二个构造函数");
    }
    public void test12 (){
        // 写法1
        using (SqlConnection cnn1 = new SqlConnection())
        {

        }
        // 写法1 的代码编译后是写法2 对写法2的封装(是写法2的语法糖)
        // 写法2  
        SqlConnection cnn = new SqlConnection();
        try
        {
            // 业务代码
        }
        catch
        {
            // 捕获错误
            throw;
        }
        finally
        {
            // 资源释放   -- 会调用析构方法
            cnn.Dispose(); // 完全释放 再次使用 需要重新创建 SqlConnection  不能直接使用 open 方法
            cnn.Close();    // 没有完全释放 使用不用重新创建 可以直接使用 open 方法打开
        }
    }
}

 

posted on 2024-05-03 10:04  流浪のwolf  阅读(1)  评论(0编辑  收藏  举报