C # "OR" event delegates return bool

I created a console for my XNA game, and I have a delegate when the command was introduced. At this point, the delegate returns bool. I declared an event inside the Console class (which returns false), and then subscribed to this event from other classes. The idea is that if none of the classes that subscribe to this event returns true, it is assumed that the user has entered an invalid command. However, if at least one of the signed classes returns true, the command is considered valid.

At the moment, only one class is taken into account to return true or false, is there a way to see the return values โ€‹โ€‹of all subscribed classes, and then their result?

Thanks,

+6
c # events delegates xna
source share
3 answers

I understood this the same way I asked this question: P

bool handled = false; foreach (Delegate d in CommandProcessed.GetInvocationList()) handled |= (bool) d.DynamicInvoke (gameTime, command.ToString()); if (!handled) { } // Command Unrecognized 

Where CommandProcessed is my event the classes subscribe to.
My delegate accepts two arguments: gametime and command string.

+3
source share

Inside the class declaring the event, you can get a list of event events (subject to a field event). Calling each of them individually will allow you to check the return value of each subscriber for an event.

For example:

 public event Func<bool> MyEvent = delegate { return false; }; ... private bool EmitMyEventAndReturnIfAnySubscriberReturnsTrue() { return MyEvent.GetInvocationList() .Cast<Func<bool>>() .Select(method => method()) .ToList() //Warning: Has side-effects .Any(ret => ret); } 

In this example, each subscriber is informed about the event - there is no short circuit if any of them answers in the affirmative. If desired, this behavior can be easily changed by removing the ToList() call.

To be honest, I really don't like events that return values; their semantics are not obvious to subscribers. I would change the design, if at all possible.

EDIT: Fixed a bug when forcing the complete execution of a sequence based on a Timwi comment.

+6
source share

I agree with the issue of events returning values, it seems to me. However, you can create a new CommandEventArgs class:

 class CommandEventArgs : EventArgs { public DateTime GameTime {get; set; } public string Command {get; set;} public bool Valid {get; set;} } 

then use an instance of this method to trigger the event, and then if the listener recognizes the command, set Valid to true. Therefore, if Valid is still false after the call, you know that the command was not recognized.

This is how .NET manages the keyboard events that you set KeyEventArgs.Handled to true to suppress any further actions that happen to the event.

0
source share

All Articles