簡體   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