简体   繁体   中英

C# Object Scope

I'm trying to understand when a object is recycled. For example, in a class I have a List declaration and a method inside this class to populate the list by declaring and initializing a temporary object and then adding this object to the list.

My confusion: Since the temporary objects were declared within the body of the method, wouldn't these objects be recycled when the method returns and thus the list which held references to them now lose their object's values? My code still keeps the object values (and presumably reference intact) after method completion.

public class CameraTest
{

    private List <Camera> cameraList;
    public CameraTest()
    {
        AddCamera();
    }

    private void AddCamera()
    {
        Camera tempCamera = new Camera();
        tempCamera.Name="Camera1";
        cameraList.Add(tempCamera);
    }

   //Why would cameraList still have the "Camera1" object here?

}

The garbage collector in .NET is non-deterministic. An object is "ready for collection" once there are no more references to it, but that doesn't mean it'll be collected right away.

In your code, cameraList has the object with name "Camera1" in it because it references it, so it prevents it to be collected, no matter the scope.

The scope is meant for variables , not for objects . Objects are references in memory, while variables are just pointers to those references. You lose the variable tempCamera , but not the object it points to

Simply said: a variable is just a pointer ("reference") to an object. While a variable may go out of scope, if another variable or object (such as your list) holds a reference to that same object, the object won't be garbage collected.

Because, while CameraTest exists, it references cameraList . While cameraList exists, it references all instances of Camera that have been added to the collection.

You added the Camera1 instance of Camera to cameraList . So there's a chain of references that will prevent Camera1 from being collected by the GC until nobody holds a reference to the CameraTest instance .

You should snag a copy of CLR Via C# and read it.

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