简体   繁体   中英

casting to a derived class and garbage collection in C#

Hey I am curious about something. If I create a derived class in a method, then return a pointer to the base class, and all other references to the fact that it is the derived class disappear, what prevents the garbage collector from garbage collecting the variables that are part of the derived class? if nothing points to the derived class variables, does that memory become instantly freed?

if i then cast the base class pointer back to the derived class, does that mean that the data in the derived class variables may no longer be there?

In implementations of C++ it's pretty common for a pointer to an object "as a derived class" and a pointer to the same object "as a base class" to be implemented as different pointers. That's not the case in the CLR; when you cast a reference to a derived class into a reference to a base class, the bits of the reference don't change. Every reference "knows" its own runtime type, so the garbage collector never gets confused.

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