2012-10-05 76 views
0

我不確定這是否允許在C#中,但我很確定我以前在其他語言中使用過。如何從數組中的子類調用正確的方法?

比方說,我有班級Parent,其中有子女Child0Child1。我製作了Parent類型的數組,其中Array[0]Child0類型,Array[1]Child1類型。在這種情況下,我該如何調用兒童的方法?當我輸入Array[0].Method()時,它會調用Parent版本的Method。我如何獲得它以調用Method的Child0版本?這可能嗎?

+1

有你嘗試了'virtual'和'override'鍵話?你有什麼嘗試?顯示類的代碼,以便我們可以看到導致行爲的原因。 – zimdanen

+0

如果您將對象創建爲父對象,則只能訪問父對象中的屬性/方法。您需要將該對象創建爲子對象以調用子方法。 – landoncz

+0

你能發表一些代碼嗎? –

回答

2

你只需要聲明一種方法,在基類的虛:

public class Parent{ 
    public virtual void Method(){ 
    ... 
    } 
} 

,並覆蓋其在heriting類:

public class Child : Parent{ 
    public override void Method(){ 
     ... 
    } 
} 

需要注意的是,如果你並不真的需要一個「標準「實現,因爲所有的繼承類都有自己的版本,所以也可以將方法設置爲抽象:

public class Parent{ 
    abstract public void Method(); 
} 

然後你沒有選擇,所有從Parent繼承的類將不得不爲Method提供一個實現,否則你將會有編譯時錯誤。

1

如果您使父級方法virtual您可以重寫您的子類中的基本方法。

public class Human 
{  
    // Virtual method 
    public virtual void Say() 
    { 
     Console.WriteLine("i am a human"); 
    } 
} 

public class Male: Human 
{   
    // Override the virtual method 
    public override void Say() 
    { 
     Console.WriteLine("i am a male"); 
     base.Draw(); // --> This will access the Say() method from the 
     //parent class.   
    } 
} 

它們添加到陣列:(本書雖然是我個人使用List<T>

Human[] x = new Human[2]; 
x[0] = new Human(); 
x[1] = new Male(); 

打印出結果:

foreach (var i in x) 
{ 
    i.Say(); 
} 

會打印出

"i am a human" // --> (parent class implementation)  
"i am a male" // --> (child class implementation) 
相關問題