开发者

What happens to controls created in a method after the method is done?

开发者 https://www.devze.com 2022-12-18 03:08 出处:网络
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 (

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消