c#如何处理静态成员的内存

How does c# handle the memory for static members

进行了大量搜索,但 none 最终澄清了我的疑问。

当使用静态 class 或方法时,c# 何时为它们分配内存?它会被释放吗?

附加问题:什么时候应该使用静态成员或class?

https://msdn.microsoft.com/en-us/library/79b3xss3.aspx

As is the case with all class types, the type information for a static class is loaded by the .NET Framework common language runtime (CLR) when the program that references the class is loaded. The program cannot specify exactly when the class is loaded. However, it is guaranteed to be loaded and to have its fields initialized and its static constructor called before the class is referenced for the first time in your program. A static constructor is only called one time, and a static class remains in memory for the lifetime of the application domain in which your program resides.

When one use a static class or method, when does c# allocates memory for them?

分配内存的不是C#,而是底层的CLR。您还应该区分内存的分配和成员的实际初始化

内存的分配可能发生在程序(EXE、DLL)加载到内存中时。这是因为在“典型”实现中,静态数据成员分配在所谓的 data 段上。这是内存的固定部分,专门用于保存永久(从 运行 时间的角度来看)数据结构。然而,一个特定的实现可能会有点不同,即使必须是某种静态 data 段,至少包含指向其他数据结构的指针。

初始化 发生在 class 首次访问之前。

And does it get deallocated at all?

没有。它们是静态的。


Bonus question: When should one use a static member or class?

旁注:这不是奖励问题,而是作为主要基于意见的问题而关闭的原因。