繁体   English   中英

当我调用方法时,为什么不调用覆盖的方法?

[英]When I call a method, why isn't the overridden method called?

我的问题是我的方法调用函数转到虚拟方法,而不是覆盖的方法。 我尝试用虚拟方法继承该类,并且在调试时没有什么不同。 什么东西少了?

public class Engine
{
    protected virtual void ExecuteCommand(string[] inputParams)
    {
        switch (inputParams[0])
        {
            case "status":
                this.PrintCharactersStatus(this.characterList);
                break;
        }
    }

    protected virtual void CreateCharacter(string[] inputParams)
    {
    }

    protected virtual void AddItem(string[] inputParams)
    {
    }

    private void ReadUserInput()
    {
        string inputLine = Console.ReadLine();
        while (inputLine != string.Empty)
        {
            string[] parameters = inputLine
                .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            ExecuteCommand(parameters);
            inputLine = Console.ReadLine();
        }
    }
}

public class Program : Engine
{
    public static void Main()
    {
        Engine engine = new Engine();
        engine.Run();
    }

    protected override void ExecuteCommand(string[] inputParams)
    {
        base.ExecuteCommand(inputParams);

        switch (inputParams[0])
        {
            case "create":
                this.CreateCharacter(inputParams);
                break;

            case "add":
                this.AddItem(inputParams);
                break;
        }
    }

您正在创建Engine而不是Program的实例-您需要做的就是将Main的第一行更改为:

Engine engine = new Program();

要使用的实现基于调用该方法的对象的执行时类型-在您现有的代码中,只有Engine.ExecuteCommand ,因此不会调用Program的代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM