.NET Does removing a parent class turn the children into “garbage”?

后端 未结 1 906
谎友^
谎友^ 2021-01-18 14:45

Suppose you have a Collection, and you\'re about to remove an item. Instance of B is referenced from an instance of A, and re

相关标签:
1条回答
  • 2021-01-18 15:16

    Provided there's no other "outside reference" to any of the instances involved (basically, no other arrow pointing coming in from outside of the picture), will the removed 'A ViewModel' instance take all the children with it?

    Yes, provided there are no references from your code to the child, it will be eligible for garbage collection, and should eventually be collected.

    If there's no other reference to A, not only it gets removed from the collection, it is marked as garbage. Am I right?

    That is not actually how this works. The GC doesn't "track garbage" - instead, it checks all of the object references from currently executing code, and walks out to find references that are currently "alive". Anything left over at that point is not alive, and then becomes eligible for collection. If the only way to reach "B" or "C", in your graph, is through that instance of "A", and you remove "A" from the collection, all of those will become eligible for GC and be found in the next appropriate GC collection.

    0 讨论(0)
提交回复
热议问题