public class MyClass {
private static MyClass heldInstance;
public MyClass() {
heldInstance = this;
}
}
假设 MyClass 的实例没有以任何其他方式作为根,这里的私有(private)静态引用是否会阻止它被垃圾收集?
最佳答案
您发布的类(class)不会被垃圾回收。您可以通过给它一个带有控制台输出的终结器来测试它:
public class MyClass
{
private static MyClass heldInstance;
public MyClass()
{
heldInstance = this;
}
~MyClass()
{
Console.WriteLine("Finalizer called");
}
}
class Program
{
static void Main(string[] args)
{
var x = new MyClass(); // object created
x = null; // object may be eliglible for garbage collection now
// theoretically, a GC could happen here, but probably not, with this little memory used
System.Threading.Thread.Sleep(5000);
// so we force a GC. Now all eligible objects will definitely be collected
GC.Collect(2,GCCollectionMode.Forced);
//however their finalizers will execute in a separate thread, so we wait for them to finish
GC.WaitForPendingFinalizers();
System.Threading.Thread.Sleep(5000);
Console.WriteLine("END");
}
}
输出将是:
END
Finalizer called
这意味着该类仅在应用程序的最终拆卸时被收集,而不是在常规垃圾收集期间。
如果您像这样创建此类的多个实例:
var x = new MyClass();
x = new MyClass();
x = new MyClass();
x = new MyClass();
然后除了最近的一个之外的所有都将被垃圾收集。
你会得到
Finalizer called
Finalizer called
Finalizer called
END
Finalizer called
关于c# - 在静态字段中引用自身的类可以被垃圾收集吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15099700/