Is there a standard way to implement Vetoable events?

I use events as part of the game model, and for the extension and the "terrain" code, I should be able to veto most actions.

More clearly, almost every method with a side effect takes the following form:

public event TryingToDoSomethingHandler TryingToDoSomething;
public event SomethingHappenedHandler   SomethingHappened;

/*
 * Returning true indicates Something happened successfully.
 */
public bool DoSomething(...)
{
  //Need a way to indicate "veto" here
  TryingToDoSomething(...);

  //Actual do it

  SomethingHappened(...);

  return true;
}

I would like to try TryingToDoSomething (...) to indicate that the registered object is an event handler (via returning false, changing the out parameter or something else). To make the code morally equivalent:

/*
 * Returning true indicates Something happened successfully.
 */
public bool DoSomethingImproved(...)
{
  //Pretty sure multicast delegates don't work this way, but you get the idea
  if(!TryingToDoSomething(...)) return false;

  //Actual do it

  SomethingHappened(...);

  return true;
}

Is there an acceptable or standard way to do this in C # /. NET?

+5
source share
2 answers

Are you thinking of canceling events? The structure uses this widely.

EventArgs, Cancel, get/set. Cancel true, .

public bool TrySomething()
{
    CancelEventArgs e = new CancelEventArgs(); 
    if (Event1 != null) Event1.Invoke(e);
    if (e.Cancel == false)
    {
        if (Event2 != null) Event2.Invoke(e);
    }
}
+6

All Articles