我正在研究垃圾收集器在 C# 中的工作原理。我对 Destructor
、Dispose
和 Finalize
方法的使用感到困惑。
根据我的研究和理解,在我的类中有一个 Destructor 方法将告诉垃圾收集器以不能在类的实例上显式调用的析构方法中提到的方式执行垃圾收集。
Dispose
方法旨在让用户控制垃圾收集。 Finalize
方法释放类使用的资源,但不释放对象本身。
我不确定我是否理解正确。请解惑。欢迎任何进一步的链接或指南。
最佳答案
析构函数隐式调用 Finalize 方法,它们在技术上是相同的。 Dispose 可用于实现 IDisposable 接口(interface)的对象。
您可能会看到:Destructors C# - MSDN
The destructor implicitly calls Finalize on the base class of the object.
来自同一链接的示例:
class Car
{
~Car() // destructor
{
// cleanup statements...
}
}
析构函数的代码隐式转换为以下代码:
protected override void Finalize()
{
try
{
// Cleanup statements...
}
finally
{
base.Finalize();
}
}
你对析构函数的理解是正确的:
来自 MSDN
The programmer has no control over when the destructor is called because this is determined by the garbage collector. The garbage collector checks for objects that are no longer being used by the application. If it considers an object eligible for destruction, it calls the destructor (if any) and reclaims the memory used to store the object. Destructors are also called when the program exits. It is possible to force garbage collection by calling Collect, but most of the time, this should be avoided because it may create performance issues.
关于c# - 析构函数、处理方法和终结方法之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13988334/