c# - 析构函数、处理方法和终结方法之间的区别

标签 c# .net destructor dispose finalize

我正在研究垃圾收集器在 C# 中的工作原理。我对 DestructorDisposeFinalize 方法的使用感到困惑。

根据我的研究和理解,在我的类中有一个 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/

相关文章:

c# - jQuery - 如何正确显示两个日期之间的所有记录?

c# - 如何自定义 ObjectQuery 的 Execute 方法?

ios - libc++ for mac os中的可能错误,当字符串obj超出范围时,不调用字符串析构函数

c++ - 关于 C++ 中自定义对象的构造函数/析构函数和新建/删除运算符

c# - 使用 C# 从 html 标签中提取文本

c# - 在 Outlook 2013 C# VSTO 项目中,为什么 Explorer SelectionChange 事件会触发两次

.net - Json.net 向包含特定类型的每个类添加属性

c# - 如何在 C# 中从 IDataReader 写入 xml 文件

c++ - 为什么使用赋值时不调用堆栈变量的析构函数?

c# - "Enforce"在 C# 中覆盖