简体   繁体   English

C#对象范围

[英]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. 例如,在一个类中,我有一个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. .NET中的垃圾收集器是不确定的。 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. 在您的代码中, cameraList在其中包含名称为“ Camera1”的对象,因为它引用了它,因此无论范围如何,它都将阻止它被收集。

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 您会丢失变量tempCamera ,但不会丢失它指向的对象

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 . 因为尽管存在CameraTest ,但它引用了cameraList While cameraList exists, it references all instances of Camera that have been added to the collection. 存在cameraList时,它引用已添加到集合中的Camera所有实例。

You added the Camera1 instance of Camera to cameraList . 您添加的摄像机1实例CameracameraList 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 . 因此,存在一系列引用,可以防止GC收集Camera1直到没有人持有对CameraTest实例的引用CameraTest

You should snag a copy of CLR Via C# and read it. 您应该通过C#获取CLR副本并阅读。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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