有什么方法可以在我的课程中订阅某个事件时收到通知,或者我是否需要在方法中包含订阅/取消订阅,例如:
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 } }
解决方法
您可以为您的活动编写自定义访问者:
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"); } }