如何从数组中的子类调用正确的方法?

时间:2012-10-05 20:35:42

标签: c# asp.net arrays parent-child

我不确定C#中是否允许这样做,但我很确定我以前用其他语言做过。

假设我有课程Parent,其中包含子Child0Child1。我创建了一个Parent类型的数组,其中Array[0]的类型为Child0,而Array[1]的类型为Child1。在这种情况下,我如何调用孩子的方法?当我输入Array[0].Method()时,它会调用Method的Parent版本。如何让它调用方法的Child0版本?这可能吗?

2 个答案:

答案 0 :(得分:2)

您只需在基类中声明Method为virtual:

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

并在heriting类中覆盖它:

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

请注意,如果您的Parent类中不需要“标准”实现,因为所有的继承类都有自己的版本,您也可以将该方法设置为抽象:

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

然后你没有选择,从Parent继承的所有类都必须提供Method的实现,否则你将有编译时错误。

答案 1 :(得分: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)