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.)
这篇关于静态成员是否曾经被垃圾收集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:静态成员是否曾经被垃圾收集?
基础教程推荐
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 如何激活MC67中的红灯 2022-01-01