当类中的某个事件订阅时,是否有任何方式可以得到通知,或者我是否需要在方法中包装订阅/取消订阅,例如:

public class MyClass : ISomeInterface
{
     public event SomeEventHandler SomeEvent; //How do I know when something subscribes?

     private void OnSomeEventSubscription(SomeEventHandler handler)
     {
          //do some work
     }

     private void OnSomeEventUnsubscription(SomeEventHandler handler)
     {
          //do some work
     }
}

而不是
public class MyClass : ISomeInterface
{
     private SomeEventHandler _someEvent;

     public void SubscribeToSomeEvent(SomeEventHandler handler)
     {
          _someEvent += handler;

          //do some work
     }

     public void UnsubscribeFromSomeEvent(SomeEventHandler handler)
     {
          _someEvent -= handler;

          //do some work
     }
}

我问这个问题的原因是,事件已经在ISomeInterface上直接公开了,但是这个特定的实现需要知道什么时候订阅/取消订阅。

最佳答案

您可以为事件编写自定义访问器:

private SomeEventHandler _someEvent;
public event SomeEventHandler SomeEvent
{
    add
    {
        _someEvent += value;
        Console.WriteLine("Someone subscribed to SomeEvent");
    }
    remove
    {
        _someEvent -= value;
        Console.WriteLine("Someone unsubscribed from SomeEvent");
    }
}

08-06 14:58