简体   繁体   中英

When creating a template class and adding an event is there any need to remove it?

Here's the code I have:

namespace X.Templates
{
    public class ABCTemplate : Grid
    {

        public ABCTemplate()
        {
            TapGestureRecognizer tap = new TapGestureRecognizer() { NumberOfTapsRequired = 1 };
            tap.Tapped += Tap_Tapped;
        }

        private void Tap_Tapped(object sender, EventArgs e)
        {
            //
        }
    }
}

Should I do anything to remove the Tap_Tapped or will it simply go away when the ABCTemplate is no longer used?

is there any need to remove it?

EventHandler is Managed resources that will been cleaned up implicitly by the garbage collector( GC ). You do not have to write code to release such resources explicitly.

So in your case, it is unnecessary to remove it manually as it will been released automatically when the parent view ending its' lifecycle (pop up from current page or remove from the page).

Of course sometimes we will see the code like

tap.Tapped -= Tap_Tapped;

This is because of code standards. And if we invoke the code in a wrong will maybe let the Event don't work any more.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM