Why are destructors in this chain of inheritance called, in order, from most received to least received?

Base on C # specification, 10.13 Destructors

"When an instance is destroyed, destructors in this case the chain of inheritance is called, in order, from most received to least received."

My questions:

why are destructors called in order from most received to least received? why aren't they called, in order, from the smallest derivative to the derivative itself or another order?

+5
source share
2 answers

Since objects are created from the least received to the most withdrawn, so they need to be torn from the most received to received.

, . , , .

, , :

public class MyBase {

  public List<SomeObject> list;

  public MyBase(){
    list = new List<SomeObject>();
    list.Add(new SomeObject());
    list.Add(new SomeObject());
    list.Add(new SomeObject());
  }

  ~MyBase() {
    foreach (SomeObject obj in list) {
      obj.Cleanup();
    }
    list.Clear();
  }

}

- :

public class MyDerived : MyBase {

  public MyDerived() {
    foreach (SomeObject obj in list) {
      obj.SomeProperty = new Handler();
    }
  }

  ~MyDerived(){
    foreach (SomeObject obj in list) {
      obj.SomeProperty.Cleanup();
    }
  }

}

, , . , .

( , IDisposable .)

+4

, , . , , .

, , , , .

+6

All Articles