2013-04-04 53 views
1

我有以下代碼:強制重寫方法基類

public partial class Root : ICustomInterface 
{ 
    public virtual void Display() 
    { 
     Console.WriteLine("Root"); 
     Console.ReadLine(); 
    } 
} 
public class Child : Root 
{ 
    public override void Display() 
    { 
     Console.WriteLine("Child"); 
     Console.ReadLine(); 
    } 
} 
class Program 
{ 
    static void Main(string[] args) 
    { 
     Root temp; 
     temp = new Root(); 
     temp.Display(); 
    } 
} 

Output: "Root" 
Desired output: "Child" 

當我實例化一個Root對象並調用Display()方法我想在Child顯示重寫的方法這是可能的。

我需要這個,因爲我必須創建一個插件,是一個擴展,基本代碼和空洞的Root類的Display()方法,當我實例化一個根對象和呼叫僅實現插件的方法Child

+3

我不認爲你完全理解繼承。如果您希望Display()方法輸出「Child」,您需要創建一個Child實例。 – 2013-04-04 09:11:03

+1

對於您編輯的部分問題,您應該看到:http://stackoverflow.com/questions/2779146/c-is-there-它是繼承的方法 - 類 - 去除 - 方法,也是這樣一個:http:// stackoverflow。com/questions/1125746/how-to-hide-remove-a-base-classs-methods-in-c – Habib 2013-04-04 09:25:54

回答

1

不,這不是可能的,你必須實例化一個子對象,而不是根

Root temp; 
temp = new Child(); 
temp.Display(); 

的,如果你不希望修改溫度,那麼你必須修改根目錄顯示方法打印「孩子」,而不是根

+0

我不想修改臨時對象。 – XandrUu 2013-04-04 09:12:26

+0

然後修改根目錄來代替顯示「child」... – 2013-04-04 09:13:04

+0

我不想這樣做,我想創建一個插件並且不修改項目的基本代碼,插件必須是一個擴展,它會使Root方法和只調用我的Child方法。 – XandrUu 2013-04-04 09:16:46

6

Display()方法我想要 在Child中顯示重寫的方法是可能的。

您需要創建Child類的實例。

Root temp; 
temp = new Child(); //here 
temp.Display(); 

目前你的對象temp持有基類的引用,它不知道孩子什麼,因此從基類的輸出。

1

由於您正在創建Root實例而不是Child實例,因此無法使用當前代碼。因此它不知道Child中的Display方法。

你需要創建一個Child類:

Root temp; 
temp = new Child(); 
temp.Display(); 
1

這不是OOP是如何工作的。您不能在基類中使用重寫的方法。如果你這樣做:

static void Main(string[] args) 
{ 
    Root temp; 
    temp = new Child(); 
    temp.Display(); 
} 

你應該得到你想要的輸出。

+0

我不想修改臨時對象。 – XandrUu 2013-04-04 09:13:11

+2

然後你不知道你在做什麼 – 2013-04-04 09:24:42

2

當我實例化一個Root對象並調用Display()方法時,我想在Child中顯示重寫的方法,這是可能的。

號假設你添加另一個類:

public class Child2 : Root 
{ 
    public override void Display() 
    { 
     Console.WriteLine("Child 2"); 
     Console.ReadLine(); 
    } 
} 

然後(Child.Display()Child2.Display())你會想到要呼籲Root例如哪種方法?