C# 对象的系统结构

C# 对象的系统结构,c#,C#,请告诉我为什么~Destruct()会一直等到代码结束才删除对象?我认为destruct必须创建一个对象并立即删除它。但是我的代码创建了10000个对象,只有这样做了,它才会删除10000个对象。为什么? using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace project6 { class

请告诉我为什么~Destruct()会一直等到代码结束才删除对象?我认为destruct必须创建一个对象并立即删除它。但是我的代码创建了10000个对象,只有这样做了,它才会删除10000个对象。为什么?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace project6
{
    class Destruct
    {
        public int x;
        public Destruct(int i)
        {
            x = i;
        }
        ~Destruct()
        {
            Console.WriteLine("\n"+ x +" - Обьект разрушен");
        }
        public void generator(int i)
        {
            Destruct obj = new Destruct(i);
        }
    }


    class Program
    {
        static void Main()
        {
            Destruct o = new Destruct(0);
            for(int a=0;a<10000;a++)
            {
                o.generator(a);    
            }
            Console.WriteLine("Готово");
            }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
命名空间项目6
{
类析构函数
{
公共int x;
公共销毁(int i)
{
x=i;
}
~Destruct()
{
控制台写入线(“\n”+x+”-öббззбзбб;
}
公共无效生成器(int i)
{
自毁obj=新自毁(i);
}
}
班级计划
{
静态void Main()
{
析构函数o=新析构函数(0);
for(int a=0;aC#使用垃圾收集来删除对象。它不一定会在每个对象都超出范围时运行-这些对象只是“排队”进行删除。这就是创建所有对象,然后删除所有对象的原因


基本上,您不知道垃圾收集器将在何时运行。

在循环之后调用~Destruct>的原因是~Destruct()函数将仅在垃圾收集器运行时调用。如果强制垃圾收集器运行它们,则对象将在超出范围时立即销毁

        for(int a=0;a<10000;a++)
        {
            o.generator(a); 

            //This will IMMEDIATLY destroy the object created by o.generator
            GC.Collect()   
        }
for(int a=0;a