简体   繁体   中英

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

My problem is that my method call function goes to the virtual method, not to the overridden one. I tried to inherit the class with the virtual method and when I debug it's nothing different. What is missing?

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

You're creating an instance of Engine , not Program - all you need to do is change the first line of Main to:

Engine engine = new Program();

The implementation to use is based on the execution-time type of the object on which the method is called - in your existing code, that's only ever Engine.ExecuteCommand , so the code in Program won't get called.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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