为什么不能调用析构函数

namespace 析构函数
{
class Program
{
static void Main(string[] args)
{
Test yu = new Test();
}
}
class Test
{
public int a;
public Test()
{
a = 20;
Console.WriteLine("我是渣渣辉");
}
~Test()
{
Console.WriteLine("成功");
}
}
}

回答

主动GC一下就可以了, GC回收的触发是有条件的. 例如物理内存不够,系统说要压缩一下, C# 0堆满了等等条件. GC相关内容请参考文档:https://docs.microsoft.com/zh-cn/dotnet/standard/garbage-collection/fundamentals, 建议通读.

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            test();
            GC.Collect();
            Console.ReadLine();
        }
        static void test()
        {
            var t = new Test();
        }
    }
    class Test
    {
        public int a;
        public Test()
        {
            a = 20;
            Console.WriteLine("我是渣渣辉");
        }
        ~Test()
        {
            Console.WriteLine("成功");
        }

    }
以上是为什么不能调用析构函数的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>