what happens if i link a method of some object to a delegate, and then dispose of the object?
Like this:
class Hun开发者_开发百科ter
{
public event Action Shoot;
public execute()
{
Form formBabySeal = new Form();
Shoot += formBabySeal.Close;
formBabySeal.Show();
formBabySeal.Close(); //Dispose Form
if (Shoot != null)
{
Shoot(); //event is null?
}
}
}
formBabySeal
is not null
just because you dispose it. So, formBabySeal.Close()
will be called.
Your code is equivalent to this when looking at what methods are called:
Form formBabySeal = new Form();
formBabySeal.Show();
formBabySeal.Close(); //Dispose Form
formBabySeal.Close();
This will close the form (first call to Close
) and the second call won't do anything, because the form is already closed.
However, as Steve points out in the comment section, your code will introduce a memory leak, because Shoot
still holds a reference to the Close
method of formBabySeal
and because of this formBabySeal
will be kept alive as long as the instance of the class Hunter
is alive.
WinDBG with SOS extensions has a way to show GCRoot of any object. This might give you more clues.
精彩评论