see this class:
class Outer
{
private Foo _foo;
public Outer()
{
_foo = new Foo();
GC.K开发者_如何学编程eepAlive(_foo);
}
}
If I create an object of class Outer, will the object be GCed?
Are you sure that you've correctly understood how KeepAlive
works?
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.
So you're instantiating an instance of Outer
. The constructor instantiates _foo
and immediately calls KeepAlive
. That KeepAlive
call ensures that _foo
is not collected in the time between when it was instantiated and when KeepAlive
was called. As soon as the KeepAlive
call has completed, _foo
is eligible for collection.
The instance of Outer
-- or any other class -- is eligible for collection as soon as it is no longer in use. Even theoretically, the call to KeepAlive
is irrelevant: it might keep _foo
alive for slightly longer, but it makes no difference to the outer class.
精彩评论