2015-12-02 195 views
0

我的問題是,我的方法調用函數轉到虛方法,而不是覆蓋的方法。我試圖用虛方法繼承這個類,當我調試它時沒有什麼不同。什麼不見​​了?當我調用一個方法時,爲什麼不調用被重寫的方法?

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

回答

3

你正在創建的Engine一個實例,而不是Program - 所有你需要做的是改變Main第一行:

Engine engine = new Program(); 

使用的實現是基於execution-調用方法的對象的實時類型 - 在您現有的代碼中,這只是Engine.ExecuteCommand,因此Program中的代碼不會被調用。

相關問題