I am a bit new to c#
so please overlook if you find it trivial. I saw the following "weird" code.
Can anybody shed a bit of light on it.
public event Action _action;
if (_action != null)
{
foreach (Action c in _action.GetInvocationList())
{
_action -= c;
}
}
Specially the _action -= c;
part.
You generally use events to notify subscribers about some action or state change that occurred on the object. By using an event, you let different subscribers react differently, and by decoupling the subscriber (and its logic) from the event generator, the object becomes reusable.
Events are user actions such as key press, clicks, mouse movements, etc., or some occurrence such as system generated notifications. Applications need to respond to events when they occur. For example, interrupts.
A delegate can be a delegate to more than one function. If you have a delegate alpha
that delegates to Alpha()
and a delegate beta
that delegates to Beta()
then gamma = alpha + beta;
is a delegate that calls Alpha()
then Beta()
. gamma - beta
produces a delegate that calls Alpha()
. It's a bit of a weird feature, to be perfectly frank.
The code you've posted is bizarre. It says "go through the list of functions in action, produce a whole pile of delegates that invoke fewer and fewer functions, and then finally assign a delegate that does nothing to action
. Why on earth would anyone do this? Just assign null
to action
and be done with it.
public event Action _action; //an event
if (_action != null) // are there any subscribers?
{
foreach (Action c in _action.GetInvocationList()) //get each subscriber
{
_action -= c; //remove its subscription to the event
}
}
It's removing the handlers for the action.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With