-4

I want to produce a void method that takes other void methods as parameters so that I can call them individually in a case-by-case basis. This method will be accessible by child classes that can call the function by name while passing void methods into it.

Like so:

public class parent_class
{
    ...
    protected void like_an_action_delegate (Action/void function_a(), Action/void function_b(), ...)
    {
        if (condition_1)
        {
            function_a();
        }
        else if (condition_2)
        {
            function_a();
        }
            ...
        }
    }
}

//new script

public class child_class : parent_class
{
    Update ()
    {
        like_an_action_delegate (void_function_a(), void_function_b(), ...);
    }
    ...some void methods here...
}

This is important because I want to be able to inherit a function that maps different functions to a set of keys (on the keyboard) like I said in a case-by-case basis.

EDIT: Thanks for introducing me to params, I'm going to learn it and report back.

Dave
  • 3
  • 2

1 Answers1

1

You can use Params key word for this,

 public void MyMethodAggregate(params Action[] actions)
 {
      actions[someInt]();
      //do other conditional stuff
 }

Another alternative might be to pass a map of { Keys , Action } dictionary

public void ProcessKeyPress(Dictionary<KeyPressEnum,Action> actionMap)
{
    actionMap[theInternalKeyVariableYouHave]( );
}

This might be a more expressive way to show what you are trying to accomplish as well

If you are trying to do this per-child if you have a set of commonly used actions that you would normally use might be better to pass them to the parent objects constructor, if that actionMap contains no specific for the pressed key then use the default behavior (would probably be useful for contextual settings where a button is used mostly for one thing)

public abstract class GameControlRequestProcessor
{
    private readonly Dictionary<KeyPressEnum, Action> _actionMap;
    private KeyPressEnum _lastKeyPressed;
    protected GameControlRequestProcessor(Dictionary<KeyPressEnum,Action> actionMap)
    { 
      _actionMap = actionMap;
    }

    protected abstract void Update( );
    protected void ProcessKeyPress(Dictionary<KeyPressEnum,Action> actionMap)
    {
      if(!actionMap.HasKey(_keyLastPressed))
      {
          if(_actionMap.HasKey(_keyLastPressed)) 
             _actionMap[keyLastPressed]();
          else 
          {
             //do something in the default case
          }
      }
      else 
        actionMap[_lastKeyPressed]();
    }
}
konkked
  • 3,161
  • 14
  • 19
  • I'd like to thank everyone for the responses, I just had a brainfart and realized that I didn't even need delegates to encapsulate my functions into one call. I didn't even need params although it can help me in the future. Sorry everyone. :/ – Dave Feb 27 '15 at 16:35