List Clear() 方法是否会破坏子项 [C#.NET]?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/278687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 21:17:02  来源:igfitidea点击:

Does the List Clear() method destroy children [C#.NET]?

c#.netmemory-managementrecursion

提问by Jon Smock

If I create a recursive list of of lists:

如果我创建一个递归列表列表:

class myList
{
  List<myList> childLists;
  List<string> things;

  //...
}

List<myList> tempList = new List<myList>();

And then later call tempList.Clear(), will it destroy all the childLists in memory, or should I create a recursive method to clear all the childLists first?

然后稍后调用 tempList.Clear(),它会销毁内存中的所有 childList,还是应该创建一个递归方法来先清除所有 childList?

采纳答案by Godeke

If no otherreferences exist to the child lists, they will be garbage collected as normal. The trick is to watch for any dangling references to the child items (databinding especially tends to go unnoticed once done).

如果不存在对子列表的其他引用,它们将像往常一样被垃圾收集。诀窍是注意对子项的任何悬空引用(数据绑定尤其容易在完成后被忽视)。

回答by Lasse V. Karlsen

You do not need to clear the sub-lists.

您不需要清除子列表。

The only thing you would have to do is if the objects in your list implements IDisposable, then you should iterate through the objects and call the .Dispose() method before clearing the list.

您唯一需要做的是,如果列表中的对象实现 IDisposable,那么您应该遍历对象并在清除列表之前调用 .Dispose() 方法。

回答by chakrit

You seem to have come from a C++ background.

您似乎来自 C++ 背景。

A read on .NET's Garbage Collectionshould clear a lot of things up for you.

阅读.NET 的 Garbage Collection应该会为您解决很多问题。

In your case, you do not need to "destroy" all the child lists. In fact, you can't even destroy or dispose a generic List object yourself in a normal good-practice .NET way. If you no longer wish to use it, then just remove all references to it. And the actual destruction of the object will be done by the garbage collector (aka GC) when it sees appropriate.

在您的情况下,您不需要“销毁”所有子列表。事实上,您甚至无法以正常的良好实践 .NET 方式自行销毁或处置通用 List 对象。如果您不再希望使用它,则只需删除对它的所有引用。对象的实际销毁将由垃圾收集器(又名 GC)在它认为合适的时候完成。

The GC is also very smart, it'll detect circular-references and a->b->c->d object trees and most things you could come up it and clean the whole object graph up properly. So you do not need to create that recursive cleaning routine.

GC 也非常聪明,它会检测循环引用和 a->b->c->d 对象树以及大多数你可以想到的东西,并正确地清理整个对象图。因此,您无需创建递归清洁例程。

But do note that the GC's behavior is undeterministic, i.e. you won't know when the actual "cleanup" will happen so if your list contains some important resources that should be freed immediately i.e. File handles, database connections, then you should explicitly "Dispose" of it, as @lassevk recommended.

但请注意,GC 的行为是不确定的,即您不知道实际“清理”何时发生,因此如果您的列表包含一些应立即释放的重要资源,即文件句柄、数据库连接,那么您应该明确地“处理” ”,正如@lassevk 所推荐的那样。