有什么方法可以在我的课程中订阅某个事件时收到通知,或者我是否需要在方法中包含订阅/取消订阅,例如:
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
上,但是这个特定的实现需要知道什么时候订阅/取消订阅。
答案 0 :(得分:10)
您可以为活动编写自定义访问者:
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");
}
}
答案 1 :(得分:1)
Thomas已经回答了这个问题,但我还想补充一点,您可能需要锁定添加删除部分中的任何关键部分,因为事件订阅绝不是线程安全的,即您不知道谁将连接到您或什么时候。 E.g:
private readonly object _objectLock = new object();
private SomeEventHandler _someEvent;
public event SomeEventHandler SomeEvent
{
add
{
lock(_objectLock)
{
_someEvent += value;
// do critical processing here, e.g. increment count, etc could also use Interlocked class.
} // End if
} // End of class
remove
{
lock(_objectLock)
{
_someEvent -= value;
// do critical processing here, e.g. increment count, etc could also use Interlocked class.
} // End if
} // End if
} // End of event