静态成员是否曾经被垃圾收集?

Do static members ever get garbage collected?(静态成员是否曾经被垃圾收集?)

本文介绍了静态成员是否曾经被垃圾收集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

静态成员变量会被垃圾回收吗?

Do static member variables ever get garbage collected?

例如,让我们使用下面的类.

For example, let's use the following class.

public class HasStatic {
    private static List<string> shared = new List<string>();

}

假设它是这样使用的:

//Startup
{
HasStatic a = new HasStatic();
HasStatic b = new HasStatic();
HasStatic c = new HasStatic();
HasStatic d = new HasStatic();
//Something
}
//Other code
//Things deep GC somewhere in here
HasStatic e = new HasStatic();

abcd 被垃圾回收时,静态成员 共享 也被收集?e 是否有可能获得 shared 的新实例?

When a, b, c, and d are garbage collected does the static member shared get collected as well? Could e possibly get a new instance of shared?

推荐答案

不,静态成员与 Type 相关联,Type 与加载它的 AppDomain 相关联.

No, static members are associated with the Type, which is associated with the AppDomain it's loaded in.

请注意,对于要初始化的类和 shared 变量,不必有 任何HasStatic 实例引用 List<string>.

Note that there doesn't have to be any instances of HasStatic for the class to be initialized and the shared variable to have a reference to a List<string>.

除非您考虑卸载 AppDomain 的情况,否则静态变量可以永远被视为 GC 根.(当然,如果改变了 HasStatic.shared 的值以引用不同的实例,第一个实例可能符合垃圾回收的条件.)

Unless you're considering situations where AppDomains get unloaded, static variables can be regarded as GC roots forever. (Of course, if something changes the value of HasStatic.shared to reference a different instance, the first instance may become eligible for garbage collection.)

这篇关于静态成员是否曾经被垃圾收集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:静态成员是否曾经被垃圾收集?

基础教程推荐