使用List< Parent>中的子方法。对象 [英] Using Child methods from a List<Parent> objects

查看:102
本文介绍了使用List< Parent>中的子方法。对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我有很多类似的方法:从 Parent s列表中,我将一个对象强制转换为正确的类型,然后绘制。这可以正常工作,但是非常笨拙,因为除强制类型转换外,每种方法都完全相同。

Currently I've got a ton of methods that are all similar: From a list of Parents, I'm casting an object to it's proper type and then Drawing it. This works fine, but is extremely unwieldy as each method is exactly identical other than the cast.

看起来像这样

public class Parent
{ 
    public virtual void Draw()
    {
        //deliberately nothing
    }
}

public class Child1 : Parent
{ 
    public override void Draw()
    {
        //draw this object, but slightly different method than Parent
    }
}

public class Child2 : Parent
{ 
    public override void Draw()
    {
        //draw this, but slightly different method than Child1 and Parent
    }
}

/////////////////////////

List<Parent> parent_list = new List<Parent>();
parent_list.Add(new Child1());
parent_list.Add(new Child2());

/////////////////////////

foreach (Parent parent in parent_list)
{
    parent.Draw(); //Would like to use child1 and child2's draw
}

/////////////////////////

///instead I'm doing a manual cast for each child class
foreach (Parent parent in parent_list)
{
    Child1 child = (Child1)parent;
    child.Draw();
}

foreach (Parent parent in parent_list)
{
    Child2 child = (Child2)parent;
    child.Draw();
}

我遇到的问题是它试图调用 Parent.Draw()当我想要它调用 Child.Draw()时,我肯定有更好的设计方法代码,但我不知道。

The issue I'm running into is that it's trying to call Parent.Draw() when I want to it to call Child.Draw() I'm positive there's a better way to design the code, but I can't figure it out.

当列表中的唯一元素时,如何优雅地调用列表中所有元素的 Draw

How can I call elegantly call Draw on all the elements of in list when the only thing in common is their parent?

推荐答案

我想您的子类是从Parent继承的(否则就不是)可以将子对象的对象添加到父集合,并可以覆盖 Draw 方法)。我也不明白为什么要在 Draw 方法中调用 this.Draw ?它将导致递归调用。您应该在那里有方法实现

I suppose your child classes are inherited from Parent (otherwise it wouldn't be possible to add child object's to parents collection and have Draw method overridden). Also I don't understand why you are calling to this.Draw inside Draw methods? It will cause recursive calls. You should have method implementations there

public class Parent 
{ 
    public virtual void Draw()
    {
       // parent implementation of Draw
    }
}

public class Child1 : Parent
{ 
    public override void Draw()
    {
        // child1 implementation of Draw
    }
}

public class Child2 : Parent
{ 
    public override void Draw()
    {
        // use base.Draw() to call parent implementation
        // child2 implementation of Draw
    }
}

然后在您这样做时

foreach (Parent parent in parent_list)
{
    parent.Draw(); 
}

由于多态性,此处将调用重写(子)方法。

Overridden (child) methods will be called here due to polymorphism.

这篇关于使用List&lt; Parent&gt;中的子方法。对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆