【问题标题】:Calling a method of a parent interface with an (optional) parameter in the child interfaces在子接口中使用(可选)参数调用父接口的方法
【发布时间】:2020-08-09 16:42:34
【问题描述】:

大家好。

我想做这样的事

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

使用此设置:

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

但我不明白这是怎么做到的。 PS:对不起,如果标题没有完全抓住这里的问题,我很难措辞这个问题。

【问题讨论】:

    标签: c# inheritance interface


    【解决方案1】:

    完全错了..因为你的接口没有定义任何可以接受参数的名为Execute的方法......你在下面的代码示例中所做的只是隐藏接口方法定义并定义@的新定义987654322@接受一个参数...

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

    你可以做什么..在你的接口中定义相同方法的重载(方法重载),如下所示,它接受Vector2 类型参数

    public interface ICommand
    {
        void Execute();
        void Execute(Vector2 direction);
    } 
    

    【讨论】:

    • 问题是,ICommand 的所有派生类都必须实现 2 个版本的重载方法。我希望能够调用 ICommand.Execute(),并让 IDirectionalCommands 和 IImpulseCommands 都调用它们的执行方法,即使 IDirectionalCommand 的执行方法需要一个参数。
    猜你喜欢
    • 2018-08-23
    • 2014-08-08
    • 1970-01-01
    • 1970-01-01
    • 2011-06-09
    • 2016-11-27
    • 2019-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多