gpt4 book ai didi

C#清零前清空列表

转载 作者:可可西里 更新时间:2023-11-01 09:06:05 25 4
gpt4 key购买 nike

今天看到一段代码,乍一看觉得很奇怪,让我重新考虑。这是代码的简化版本:

if(list != null){
list.Clear();
list = null;
}

我的想法是,为什么不简单地替换它:

list = null;

我读了一点,我明白清除列表将删除对允许 GC 执行它的对象的引用,但不会“调整大小”。为该列表分配的内存保持不变。

另一方面,设置为 null 也会删除对列表的引用(并因此删除其项目),同时允许 GC 执行它的操作。

所以我一直在努力找出一个理由,就像第一个街区一样。我想到的一种情况是,如果您对列表有两个引用。第一个 block 将清除列表中的项目,因此即使第二个引用仍然存在,GC 仍然可以清除为项目分配的内存。

不过,我觉得这有什么奇怪的,所以我想知道我提到的场景是否有意义?

此外,是否还有任何其他情况需要我们在将引用设置为 null 之前对列表进行 Clear() 操作?

最后,如果我提到的场景有意义,那么确保我们不会同时持有对该列表的多个引用以及我们将如何(明确地)做到这一点不是更好吗?

编辑:我明白了清除列表和清空列表的区别。我很好奇,想知道 GC 内部是否有某些东西可以使它在 Nulling 之前有理由清除。

最佳答案

list.Clear() 在您的场景中不是必需的(其中 Listprivate 并且仅在 < 类(class))。

关于可达性/事件对象的一个​​很好的介绍级链接是 http://levibotelho.com/development/how-does-the-garbage-collector-work :

How does the garbage collector identify garbage?

In Microsoft’s implementation of the .NET framework the garbage collector determines if an object is garbage by examining the reference type variables pointing to it. In the context of the garbage collector, reference type variables are known as “roots”. Examples of roots include:

  • A reference on the stack
  • A reference in a static variable
  • A reference in another object on the managed heap that is not eligible for garbage collection
  • A reference in the form of a local variable in a method

此上下文中的关键位是托管堆上不符合垃圾回收条件的另一个对象中的引用。因此,如果 List 符合收集条件(并且列表中的对象未在别处引用),则 List 中的那些对象也符合收集条件。

换句话说,GC 将意识到 list 及其内容在同一遍是不可访问的。

那么,有没有 list.Clear() 有用的实例?是的。如果您有两个对单个 List 的引用(例如,作为两个不同对象中的两个字段),这可能很有用。其中一个引用可能希望以其他引用也受到影响的方式清除列表 - list.Clear() 是完美的。

关于C#清零前清空列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50499821/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com