清理包含另一个列表的对象的列表

Clean up list with objects holding another list

我想知道如何清理包含另一个列表的对象的列表。

像这样:

List<Foo> FooCollection = new List<Foo>();

Foo foo1 = new Foo(new List<Bar>());
Foo foo2 = new Foo(new List<Bar>());

FooCollection.Add(foo1);
FooCollection.Add(foo2);

够了吗?

FooCollection = null;

这取决于你是否想在后面的代码中使用FooCollection

// reuse the same object
FooCollection.Clear();
// start of with new collection
FooCollection = new List<Foo>();


FooCollection = null;

我不建议设置 FooCollection = null,因为使用 List 方法,如 FooCollection.Add() 会抛出异常。

您应该使用 .Clear();new List<Foo>();

基于this benchmark最快的方法是:

FooCollection = new List<Foo>();

如果您确定不再需要 FooCollection,则可以使用 FooColleciton = null。如果你想小心,GC 释放内存,你可以调用 GC.Collect();

GC Collect Reference

在这里你可以找到一些提示,什么时候可以强制垃圾收集器:

When is it acceptable to call GC.Collect?