When should I create a destructor?

2019-01-01 14:43发布

For example:

public class Person
{
    public Person()
    {
    }

    ~Person()
    {
    }
}

When should I manually create a destructor? When have you needed to create a destructor?

标签: c# destructor
8条回答
何处买醉
2楼-- · 2019-01-01 15:03

The C# language calls these "destructors", but most people call them "finalizers" since that is their .NET name and it reduces confusion with C++ destructors (which are quite different).

How to Implement IDisposable and Finalizers: 3 Easy Rules

查看更多
还给你的自由
3楼-- · 2019-01-01 15:09

It's called a destructor/finalizer, and is usually created when implementing the Disposed pattern.

It's a fallback solution when the user of your class forgets to call Dispose, to make sure that (eventually) your resources gets released, but you do not have any guarantee as to when the destructor is called.

In this Stack Overflow question, the accepted answer correctly shows how to implement the dispose pattern. This is only needed if your class contain any unhandeled resources that the garbage collector does not manage to clean up itself.

A good practice is to not implement a finalizer without also giving the user of the class the possibility to manually Disposing the object to free the resources right away.

查看更多
笑指拈花
4楼-- · 2019-01-01 15:10

You don't need one unless your class maintains unmanaged resources like Windows file handles.

查看更多
大哥的爱人
5楼-- · 2019-01-01 15:13

It's called a "finalizer", and you should usually only create one for a class whose state (i.e.: fields) include unmanaged resources (i.e.: pointers to handles retrieved via p/invoke calls). However, in .NET 2.0 and later, there's actually a better way to deal with clean-up of unmanaged resources: SafeHandle. Given this, you should pretty much never need to write a finalizer again.

查看更多
梦寄多情
6楼-- · 2019-01-01 15:15

When you have unmanaged resources and you need to make sure they will be cleaned up when your object goes away. Good example would be COM objects or File Handlers.

查看更多
刘海飞了
7楼-- · 2019-01-01 15:15

I have used a destructor (for debug purposes only) to see if an object was being purged from memory in the scope of a WPF application. I was unsure if garbage collection was truly purging the object from memory, and this was a good way to verify.

查看更多
登录 后发表回答