列表是否清除删除先前包含的对象 [英] Does a list clear delete the objects previously contained
问题描述
想象我有:
List<MyObject> MyList = new List<MyObject>();
MyObject obj1 = new MyObject();
MyObject obj2 = new MyObject();
MyList.Add(obj1);
MyList.Add(obj2);
有
MyList.Clear();
删除实例化的对象:'obj1','obj2'吗?还是将它们保留在内存中,但列表现在为空?
Delete the instantiated : 'obj1','obj2' ? Or are they kept in the memory but the list is just now empty ?
推荐答案
只要您有对对象的引用,就可以在您的代码中访问它,因为它在内存中并且垃圾回收器没有在收集它.所以答案是否,它们会保留在内存中
as far as you have a reference to an object and you can access it in your code it is there in memory and garbage collector is not collecting it. so the answer is NO, they are kept in the memory
您可以在此处了解更多信息.
you can read more about garbage collection here.
如果代码是这样的
List<MyObject> MyList = new List<MyObject>();
MyList.Add(new MyObject());
MyList.Add(new MyObject());
然后,当您调用MyList.Clear()
时,您没有引用创建的MyObject
,因此垃圾收集器将在下次运行时收集它们并将其从内存中删除.
如果要在清除列表后从内存中删除obj1
和obj2
,则应使用
then when you call MyList.Clear()
you have no reference to your created MyObject
s so garbage collector will collect them and delete them from memory in it's next run.
if you want to remove obj1
and obj2
from memory after clearing list you should use
obj1 = null;
obj2 = null;
GC.Collect()
但是要注意强制垃圾回收的后果.
but be aware of consequences of forcing garbage collection.
这篇关于列表是否清除删除先前包含的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!