Private field captured in anonymous delegate

前端 未结 3 1950
傲寒
傲寒 2021-02-07 21:49
class A
{
   public event EventHandler AEvent;
}
class B
{
   private A _foo;
   private int _bar;

   public void AttachToAEvent()
   {
      _foo.AEvent += delegate()
         


        
3条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-07 21:55

    If you add an anonymous method to an event and want to deference it, you will have to set the event to null or store your delegate in a list so you can later "-=" it from your event.

    But yes, you can get a "memory leak" from objects referenced in a delegate that is attached to an event.

提交回复
热议问题