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();
当 a、b、c 和 d 被垃圾回收时,静态成员 共享 也被收集?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.)
这篇关于静态成员是否曾经被垃圾收集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:静态成员是否曾经被垃圾收集?
基础教程推荐
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 将数据集转换为列表 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 如果条件可以为空 2022-01-01
- 从 C# 控制相机设备 2022-01-01
