Destructors are rarely used in C#, so many people have forgotten about them, although they are of little use and are useless to study.
One. Characteristics of destructors:
Destructors can only exist in classes, not structures; The destructor cannot have any modifiers, including access control modifiers, static modifiers, abstract modifiers, virtual modifiers, etc.; The destructor has no parameters, which means that there can be no overload.
Two. When to call the destructor:
The destructor is called when the object is recycled by the garbage collector, but the garbage collector has a characteristic, it is lazy, It does not recycle the variable immediately after it has left the scope and lifetime, but only when it thinks it is appropriate, usually when memory is tight. For example:
After the method btn_Click returns, de should be terminated, but its destructor is not called, indicating that the garbage collector did not recycle it; When you close the form, the destructor is executed, indicating that at the end of the program, the garbage collector is reluctantly forced to recycle it (^-^). Of course, we can call GC.Collect() to force recycling:
When you click btn1, de1 and new Demo() are terminated and the destructor is called. de2 has not yet expired its life period, so even if the GC.Collect method is called, it will not be recycled; when the btn1_Click returns, de2 has expired its life period, but due to the laziness of the garbage collector, it is still not recycled; It is not until btn2 calls the GC.Collect method that de2 is reclaimed and its destructor is called.
One way to prevent destructor calls is to implement the IDisposable interface, which defines a unique method: Dispose(). This prevents the destructor from being called internally, which means that if you are bored, you can implement this interface without calling the GC.SuppressFinalize(^-^), which is meaningless because it does not block the destructor:
Now the destructor of de1 will not be called.
Three. The essence of the destructor:
A destructor is essentially a method that takes the form of:
Usually we think that destructors can only be called by the system, not by the programmers themselves, but this is not entirely true, and destructors can also be called explicitly, after all, it is just a method:
Destructors are not required unless unmanaged resources are opened in the class
|