문제

Since my first lessons about C# classes I've learned that not only I cannot invoke the Finalize() method of a class explicitly(it is called by the Garbage Collector), but I'm not even allowed to implement it in my custom classes.
The thing that makes me a bit confused is that in MSDN like here -

By default, the Object.Finalize method does nothing. If you want the garbage collector to perform cleanup operations on your object before it reclaims the object's memory, you must override this method in your class.

I've found numerous places that suggest something else. Can anyone clarify why is that?

도움이 되었습니까?

해결책

In the same MSDN page you can read:

You cannot override the Finalize method in the C# or C++ programming languages. In C#, use destructor syntax to implement the Finalize method. In version 2.0 of the .NET Framework, C++ provides its own syntax for implementing the Finalize method, as described in Destructors and Finalizers in Visual C++. In earlier versions, C++ used destructor syntax for the Finalize method, as C# does.

It means that the Finalize() method is what will be called by the Garbage Collector but it's hidden by the friendly syntax of destructors. What you'll write as ClassName.~ClassName() will be rewritten as ClassName.Finalize() by the compiler.

EDIT
To make the point clear this is the actual syntax to implement the finalizer in C#:

class MyClass
{
    ~MyClass()
    {
    }
}

Usually you do not even need to implement your finalizer method (and it can even hurts performance) but you'll implement the Dispose pattern.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top