0

Good day everyone.

I wanna be able to do something like this

public class CommandExecutor
{
    public List<ICommand> _commandList = new List<ICommand>()
    
    public void ExecuteCommands()
    {
        for(int i = 0; i < _commandList.Count; i++)
        {
             _commandList[i].Execute();
        }
    }
}

With this setup:

public interface ICommand
{
    void Execute();
}

public interface IDirectionalCommand : ICommand
{
    
}

public interface IImpulseCommand : ICommand
{
    
}

public class ExampleCommand1 : IImpulseCommand
{
    public void Execute()
    {
        DoStuff();
    }
}

public class ExampleCommand2 : IDirectionalCommand
{
    public void Execute(Vector2 direction)
    {
        DoStuff(direction);
    }
}

But I don't understand how this could be done. PS: sorry if the title doesn't fully capture the question here, I'm having a hard time wording this problem.

1 Answer 1

1

That's wrong totally .. cause your interface have not defined any method named Execute which could accept a parameter ... what you are doing below code sample is nothing but hiding the interface method definition and defining a new definition of Execute() which accepts a parameter ...

public class ExampleCommand2 : IDirectionalCommand
{
    public void Execute(Vector2 direction)
    {
        DoStuff(direction);
    }
}

What you can do .. define a overload of same method (Method Overloading) in your interface like below which accepts a Vector2 type argument

public interface ICommand
{
    void Execute();
    void Execute(Vector2 direction);
} 
1
  • The problem is, all deriving classes of ICommand would then have to implement 2 versions of the overload method. I would like to be able to call ICommand.Execute(), and have both IDirectionalCommands and IImpulseCommands call their execute method, even though the execute method of IDirectionalCommand requires a parameter.
    – Thrindil
    Aug 9, 2020 at 17:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.