for example in this code:
void ButtonCreator()
{
Button elboton = new Butto开发者_JAVA技巧n();
}
what happens with elboton
after I call this method?
If they're not referenced by some other object (e.g. a container), then they become unreachable and are eligible for collection by the garbage collector. This is the same as creating any other object.
Note that the System.Windows.Forms.Control
class (and its subclasses like Button
) all implement the IDisposable
interface, so the easiest way to make sure any unmanaged resources associated with the Button
are released is to use a using
block, like so:
using(Button elboton = new Button()) {
// Do whatever you need to do
}
// elboton is now disposed
However, any managed resources associated with the object won't be reclaimed until the GC runs, regardless of whether or not you use a using
block.
All references to it are destroyed and in turn the garbage collector will eventually gobble it up. If you assign that button to exist in some other context (add a reference to it that last beyond the scope of this method) it will stay.
There will be no reference on that instance and it will be cleaned up by the GC after a while...
In your example elboton
will be collected by the GC (garbage collector) when the next GC iteration starts. This is because it is not referenced just after ButtonCreator() finishes.
精彩评论