2010-02-17 237 views
-2

如何在C#中創建一個子類的實例?兒童班的實例?

public class Parent 
{ 
    public virtual void test() 
    { 
     Console.WriteLine("this is parent"); 
    } 
} 

public class Child : Parent 
{ 
    public override void test() 
    { 
     Console.WriteLine("this is from child"); 
    } 
} 

public static void main() 
{ 
    //Which one is right below? 

    Child ch = new Child(); 

    Parent pa = new Parent(); 

    ch = new Parent(); 

    pa = new Child(); 

    ch.test(); 

    pa.test(); 
} 
+2

請加價的代碼! – Foole 2010-02-17 11:38:44

+0

^^^酷,T先生評論! ;-) – 2010-02-17 11:39:32

回答

3

在你的代碼有四個實例,這些都意味着略有不同的事情:

// create a new instance of child, treat it as an instance of type child 
Child ch = new Child(); 

// create a new instance of parent, treat it as an instance of parent 
Parent pa = new Parent(); 

// this will not compile; you cannot store a less specialized type in a variable 
// declared as a more specialized type 
Child ch = new Parent(); 

// create a new instance of child, but treat it as its base type, parent 
Parent pa = new Child(); 

哪一個(這三個是工作的)這是正確的取決於你想要達到的目標。

注意以下兩種情況下都打印「這是孩子」:

Child ch = new Child(); 
ch.test(); 

Parent pa = new Child(); 
pa.test(); 
2

如果你想的Child一個實例,然後new Child()是做正確的事。但是,由於ChildParent的專業化版本,因此您可以通過ChildParent參考(在您的示例中爲chpa)來引用它。

因此,您必須決定是否要以ChildParent的身份訪問該實例。

如果你

Child ch = new Child(); 

你有一個參考,Child型指向的chChild一個實例。

如果你

Parent pa = new Child(); 

你有一個參考,Parent型指向的paChild一個實例。即您正在利用繼承在ParentChild之間建立「是」關係的事實。

換句話說,Child類型是Parent的專業化。因此可以在需要Parent實例的任何地方使用Child的實例。

+0

我想去爲孩子的實例...喜歡超過4我需要打電話? – SmartestVEGA 2010-02-17 11:44:32

+1

如果你調用'new Child()',你會得到一個'Child'類型的實例,但正如我所說的,你可以使用'Child'或'Parent'類型的引用。除了創建實例,你還想完成什麼? – 2010-02-17 11:47:41

+0

你是指父母或小孩的引用類型是什麼意思?引用類型是指「=」符號的左側部分嗎? – SmartestVEGA 2010-02-17 11:53:41

1

這往往是更根本的,比你想的! 我建議你閱讀紙質這也解釋了你繼承&多態性,如msdnmsdncodeproject

對我來說,更多的是給予的解釋,而不是解決方案......