C#析构函数与Dispose

有几种不同的操作方式

方式一:


namespace ConsoleApp1
{
    class Test
    {
        ~Test()// 析构函数
        {
            Console.WriteLine("~Test()析构函数");
        }
    }
 
    class Program
    {
       
        static void Main(string[] args)
        {
            Test f = new Test();
            f = null;
            GC.Collect();
            Console.WriteLine("读取按键中");
            Console.Read();
            Console.WriteLine("读取到按键");
            Console.WriteLine("程序结束");
 
        }
    }
}
 

方式二:

    class Test
    {
        ~Test()// 析构函数
        {
            Console.WriteLine("~Test()析构函数");
        }
    }

    class Program
    {
       
        static void Main(string[] args)
        {
            Test f = new Test();
            //f = null;
            GC.Collect();
            Console.WriteLine("读取按键中");
            Console.Read();
            Console.WriteLine("读取到按键");
            Console.WriteLine("程序结束");

        }
    }

方式三:

class Test:IDisposable
{
    ~Test()// 析构函数
    {
        Console.WriteLine("~Test()析构函数");
    }
 
    public void Dispose()
    {
        Console.WriteLine("Dispose()");
        GC.SuppressFinalize(this);
        //throw new NotImplementedException();
    }
}
 
class Program
{
   
    static void Main(string[] args)
    {
        using (Test f = new Test())
        {
            
        }
        GC.Collect();
        Console.WriteLine("读取按键中");
        Console.Read();
        Console.WriteLine("读取到按键");
        Console.WriteLine("程序结束");
 
    }
}

方式四:

    class Test:IDisposable
    {
        ~Test()// 析构函数
        {
            Console.WriteLine("~Test()析构函数");
        }

        public void Dispose()
        {
            Console.WriteLine("Dispose()");//throw new NotImplementedException();
        }
    }

    class Program
    {
       
        static void Main(string[] args)
        {
            using (Test f = new Test())
            {
                
            }
            GC.Collect();
            Console.WriteLine("读取按键中");
            Console.Read();
            Console.WriteLine("读取到按键");
            Console.WriteLine("程序结束");

        }
    }

其它:直接按控制台关闭按钮,是不会调用析构函数的。
注:SuppressFinalize是取消执行终结器(析构函数)的意思。

原文地址:https://www.cnblogs.com/zhaogaojian/p/8575393.html