【问题标题】:When I call a method, why isn't the overridden method called?当我调用一个方法时,为什么不调用被覆盖的方法?
【发布时间】:2016-03-07 01:35:48
【问题描述】:

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

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

【问题讨论】:

    标签: c# visual-studio class oop


    【解决方案1】:

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

    Engine engine = new Program();
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-13
      • 2017-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-22
      • 2020-09-20
      相关资源
      最近更新 更多