Thrindil
Thrindil

Reputation: 143

Calling a method of a parent interface with an (optional) parameter in the child interfaces

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.

Upvotes: 0

Views: 174

Answers (1)

Rahul
Rahul

Reputation: 77896

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);
} 

Upvotes: 1

Related Questions