简体   繁体   中英

Inheritance and Destructors in C#

According to this , it states that Destructors cannot be inherited or overloaded. In my case, for all subclasses, the destructors will be identical. Is this pretty much telling me that I must define the same destructor in each sub class. There is no way that I can declare the destructor in the base class and have the handle the destruction? Say I have something like this:

class A
{
    ~A()
    {
        SomethingA();
    }

}

class B : A
{

}

B b = new B();

When B is destroyed, its destructor wont be called?

According to this, it states that Destructors cannot be inherited or overloaded.

Correct. Destructors are not inheritable members, and are not virtual and so cannot be overridden. They always have the same signature so they cannot be overloaded.

In my case, for all subclasses, the destructors will be identical.

The fact that you are asking such a basic question is telling me that you should not be implementing a destructor in the first place. Implementing a destructor correctly is one of the hardest things to do in C# in all but the most trivial cases. Why do you believe that you need to implement a destructor?

Is this pretty much telling me that I must define the same destructor in each sub class?

No, not at all. How did you arrive at that conclusion from the fact that destructors are not inherited?

There is no way that I can declare the destructor in the base class and have the handle the destruction?

Sure, that's a sensible thing to do, provided that you're bent on implementing a destructor in the first place.

When B is destroyed, its destructor won't be called?

That is incorrect.

It occurs to me that it would have taken you a lot less time to try it yourself than to ask the question here and wait for a response.

When does the destructors actually get called? Is it on garbage collection, when the variable falls out of scope?

My earlier conjecture is correct. You definitely should not be implementing a destructor until you deeply understand the entire garbage collection process. The fact that you believe that variables are collected when they fall out of scope, for example, indicates that you don't understand this deeply enough to write a correct destructor.

When an object is determined to be unreachable from a gc root by the collector, and the object has a finalizer that has not been suppressed then the object is promoted to the next generation by placing it on the finalization queue for servicing by the finalizer thread. If not, its memory is reclaimed.

When the finalizer thread gets around to running, it runs all the destructors of the object. (Destructors will run in order from most derived to least derived.) After that process the object then may or may not be unreachable and finalization may or may not be suppressed. If the object is determined to be unreachable then the whole process starts again.

I cannot emphasize enough how well you need to understand the GC process in order to do this correctly. When you write a destructor it runs in an environment where nothing makes sense . All the references in the object might be to objects that are only rooted by the finalizer queue; normally all references are to live things. References might be to objects that are already finalized. Destructors run on a different thread. Destructors run even if the constructor failed, so the object might not even be constructed properly. Fields of non-atomic value types may be only partially written -- it is entirely possible for a double field to have only four of its bytes set by the constructor when the thread is aborted; the finalizer will see that partially-written field. Destructors run even if the object was placed in an inconsistent state by an aborted transaction. And so on. You have to be extremely defensive when writing a destructor.

This answer might also help:

When should I create a destructor?

It's not a destructor in C#. It's known as a Finializer; and when it is called is non-deterministic. You actually can't count on it to be called at all.

Finalizers are used as a last resort to clean up unmanaged resources. You should look into the Dispose pattern .

The finalizer you defined in A will be called when an instance of B is destroyed.

If you define a finalizer in both A and B, the most specific finalizer (B) will run first, then the least specific (A).

I've been doing .NET programming for close to a decade. The only time I implemented a finalizer, it ended up being a cause for a memory leak and nothing else. You almost never need them.

A quick console app can help test this sort of thing.

using System;

class A
{
    ~A() => Console.WriteLine("~A");       
}

class B : A
{
    ~B() => Console.WriteLine("~B");
}

public class Program
{
    public static void Main() => new B();        
}

The output might be...

~B
~A

If you define a destructor for B, it will be called, followed by A's. See the example at the bottom of the link you provided .

好吧,我不知道析构函数,但是你有其他有用的方法可以清理IDisposable中的Finalize()和Dispose()。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM