c# - 正确使用析构函数c#

标签 c# destructor dispose

所以我一直在研究为我编写的类实现析构函数,但我不确定如何真正释放内存,或者这是否会由垃圾收集处理。

class AutomatedTest
{
   public bool testComplete = false;
   public bool testStopRequest = false;

   public List<Command> commandList = new List<Command>();

   private bool loggingEnabled = false;
   ...


   public AutomatedTest(TestList testToCreate)
   {
       // Create a list of Command objects and add them to the list
   }
}  

类的使用方式:

for(int numTests = 0; numTests < 20; numTests++)
{
    AutomatedTest test1 = new AutomatedTest(TestList._1DayTest);
    RunAutoTest(test1);

    AutomatedTest test2 = new AutomatedTest(TestList._2DayTest);
    RunAutoTest(test2);

    AutomatedTest test3 = new AutomatedTest(TestList._3DayTest);
    RunAutoTest(test3);

    AutomatedTest test4 = new AutomatedTest(TestList._4DayTest);
    RunAutoTest(test4);
}  

因此创建并运行了 4 个对象,并执行了 20 次。
我的问题是我应该如何正确处理/销毁这些对象?我不想假设这些是垃圾收集的,但我是实现析构函数的新手。

最佳答案

只要您不使用任何实现 IDisposable 的对象,您就不必手动处理或销毁。

关于c# - 正确使用析构函数c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10356669/

相关文章:

c++ - 调用对象的析构函数是否等同于在对象上调用delete?

.net - 管理线程之间的ObjectContext生存时间

c# - 没有控制台窗口的 AppServiceBridge

c# - 无法更新实体中的外键

c# - 我可以使用什么来获取超出 String.Format 的名称字符串模板?

c# - 这是什么??这里的符号意思

c++ - 有没有办法让 C++ 类在开始执行析构函数之前自动执行一个方法?

C++:临时参数的生命周期?

c# - 我什么时候需要管理托管资源?

c# - 有没有办法在不关闭 StreamWriter 的情况下关闭其 BaseStream?