查看此类:
class Outer
{
private Foo _foo;
public Outer()
{
_foo = new Foo();
GC.KeepAlive(_foo);
}
}
如果我创建一个 Outer 类的对象,该对象会被 GC 吗?
最佳答案
您确定您已正确理解 KeepAlive
有效吗?
References the specified object, which makes it ineligible for garbage collection from the start of the current routine to the point where this method is called.
因此,您正在实例化 Outer
的实例。构造函数实例化 _foo
并立即调用 KeepAlive
。该 KeepAlive
调用可确保 _foo
在实例化和调用 KeepAlive
之间的时间内不会被收集。一旦 KeepAlive
调用完成,_foo
就符合收集条件。
Outer
的实例(或任何其他类)一旦不再使用,就可以被收集。即使从理论上讲,对 KeepAlive
的调用也是无关紧要的:它可能会使 _foo
保持存活稍微的时间,但这对外部类没有任何影响。
关于.net - 如果类成员在C#中KeepAlived,外部对象是否会被GC?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5024680/