2013-08-16 132 views
1

「假設下面的代碼:從「base.base」類調用方法?

public class MultiplasHerancas 
{ 
    static GrandFather grandFather = new GrandFather(); 
    static Father father = new Father(); 
    static Child child = new Child(); 

    public static void Test() 
    { 
     grandFather.WhoAreYou(); 
     father.WhoAreYou(); 
     child.WhoAreYou(); 

     GrandFather anotherGrandFather = (GrandFather)child; 
     anotherGrandFather.WhoAreYou(); // Writes "I am a child" 
    } 

} 

public class GrandFather 
{ 
    public virtual void WhoAreYou() 
    { 
     Console.WriteLine("I am a GrandFather"); 
    } 
} 

public class Father: GrandFather 
{ 
    public override void WhoAreYou() 
    { 
     Console.WriteLine("I am a Father"); 
    } 
} 

public class Child : Father 
{ 
    public override void WhoAreYou() 
    { 
     Console.WriteLine("I am a Child"); 

    } 
} 

我想打印‘‘對象

我怎麼能這樣做Child對象執行上一個方法’我是爺爺’,從」孩子基地.base「類?我知道我可以做它執行基本方法(它會打印」我是一個父親「),但我想打印」我是一個祖父「!如果有辦法做到這一點,是否在OOP設計中推薦?

注意:我不使用/將會使用這種方法,我只是想加強知識的繼承。

回答

5

這隻能使用Method Hiding可能 -

public class GrandFather 
{ 
    public virtual void WhoAreYou() 
    { 
     Console.WriteLine("I am a GrandFather"); 
    } 
} 

public class Father : GrandFather 
{ 
    public new void WhoAreYou() 
    { 
     Console.WriteLine("I am a Father"); 
    } 
} 

public class Child : Father 
{ 
    public new void WhoAreYou() 
    { 
     Console.WriteLine("I am a Child");    
    } 
} 

,並調用它像這 -

Child child = new Child(); 
((GrandFather)child).WhoAreYou(); 

使用new關鍵字hides the inherited member of base class in derived class

2

嘗試使用「新」的關鍵字,而不是「覆蓋」,並刪除方法「虛」的關鍵字;)

0

這個程序在運行時會報錯。 確保孩子的對象會引用父類,然後使用引用類型強制調用方法 例如:child child = new grandfather();/這裏我們創建引用父類的子實例。/ ((爺爺)child).WhoAreYou();/*現在我們可以使用引用類型*/ 否則它們會在祖父類型轉換下顯示錯誤。