简体   繁体   English

为什么物体还活着?

[英]Why is object still alive?

Just doing some practice and was breakpointing through this example. 只是做一些练习,并通过此示例断点。 I found that the references of earlier created list members was still alive, why? 我发现先前创建的列表成员的引用仍然有效,为什么?

The anotherShoe and newShoe still had values that were assigned to their reference members however as you can see, the real objects was cleared. anotherShoenewShoe仍然具有分配给其引用成员的值,但是,如您所见,实际对象已清除。 I know I can assign them null values but aren't they automatically nulled/garbage collected when their reference objects have been List<T>.Clear() ? 我知道我可以为它们分配空值,但是当它们的引用对象为List<T>.Clear()时,它们不是自动归零/收集垃圾吗?

Thank you. 谢谢。

 List<Shoe> shoeCloset = new List<Shoe>();
            shoeCloset.Add(new Shoe() { styles = Styles.Sneakers, colour = "Red" });
            shoeCloset.Add(new Shoe() { styles = Styles.Sandals, colour = "Green" });
            shoeCloset.Add(new Shoe() { styles = Styles.Flipflops, colour = "Yellow"});
            shoeCloset.Add(new Shoe() { styles = Styles.Loafers, colour = "Brown" });
            shoeCloset.Add(new Shoe() { styles = Styles.Wingtips, colour = "Blue" });

            //int numberOfShoes = shoeCloset.Count;
            //foreach (Shoe shoe in shoeCloset)
            //{
            //    shoe.styles = Styles.Sneakers;
            //    shoe.colour = "White";
            //}

            shoeCloset.RemoveAt(3);

            Shoe newShoe = shoeCloset[2];
            Shoe anotherShoe = shoeCloset[1];
            anotherShoe.colour = "Grey";
            anotherShoe.colour = "Green";
            if (shoeCloset.Contains(anotherShoe))
            {
                Console.WriteLine("Contains another shoe");
            }

            shoeCloset.Clear();
            anotherShoe.ToString(); //<---this still contains values after shoeCloset has been cleared.
            newShoe.ToString();     //<---this still contains values after shoeCloset has been cleared.

Object instances are garbage collected when there is no possible way for any executing code to ever access them again. 当任何执行代码都无法再次访问它们时,将对对象实例进行垃圾回收。 Since you're holding onto references to these two objects through two local variables that are still in scope, those objects are accessible, and thus not eligible for garbage collection. 由于您通过两个仍在范围内的局部变量来保持对这两个对象的引用,因此这些对象是可访问的,因此不符合垃圾回收的条件。

The whole point of garbage collection is for you to not have to worry about it. 垃圾收集的全部目的是让您不必担心它。 You will never, ever (barring a few edge cases like unsafe code and weak references), try to access an object and find out that the object you're trying to access has been garbage collected. 您将永远不会(除非遇到一些unsafe代码和弱引用),否则将尝试访问对象并发现您尝试访问的对象已被垃圾回收。

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

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