:
- , , , , . , , , . , , , , .
- , , , . , Linq,
.Contains .
The first case may look like the code below. This will create a new delegate chain in the temporary variable with the delegate you want to delete, delete, and then compare the temporary chain with the existing chain. If they match, there was no delegate.
private EventHandler _Changed;
public event EventHandler Changed
{
add
{
_Changed += value;
}
remove
{
EventHandler temp = _Changed - value;
if (_Changed == null || temp == _Changed)
throw new InvalidOperationException(
"Delegate is not subscribed, cannot unsubscribe");
_Changed = temp;
}
}
The second, like the code below, will just see if the delegate you want to cancel is present in the delegate chain.
private EventHandler _Changed;
public event EventHandler Changed
{
add
{
_Changed += value;
}
remove
{
if (_Changed == null || !_Changed.GetInvocationList().Contains(value))
throw new InvalidOperationException(
"Delegate is not subscribed, cannot unsubscribe");
_Changed -= value;
}
}
Please note that if you want, use the same code to handle the case when a delegate is added twice.
source
share