2010-02-17 69 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

对我来说,更多的是给予的解释,而不是解决方案......