与事件处理程序会发生什么,当一个对象超出范围?对象、范围、发生、事件

2023-09-03 06:27:31 作者:初颜

比方说,我们有如下设置:

Let's say we have the following setup:

public class ClassA
{
   public event EventHandler SomeEvent;
}

public class ClassB : IDisposable
{
   public void SomeMethod(ClassA value)
   {
      value.SomeEvent += (s, e) => { DoSomething(); };
   }

   void DoSomething() { }

   void Dispose() { }
}

public static class Program
{
   static void Main()
   {
      var a = new ClassA();

      using (var b = new ClassB())
         b.SomeMethod(a);

      // POINT OF QUESTION!!
   }
}

当事件 SomeEvent 点问题后,提出了会发生什么情况?

What happens when the event SomeEvent is raised after the "POINT OF QUESTION"?

推荐答案

它会调用释放对象的方法。这就是为什么它是重要退订。它甚至可以导致内存泄漏。

It will call method of disposed object. That's why it is important to unsubscribe. It even can lead to memory leaks.