访问不同子类的ArrayList中的正确函数

1 c# arraylist

说我有以下三个类:

家长班:

public class ParentClass {
    public void foo() {
        Debug.Log("Parent called!");
    }
}
Run Code Online (Sandbox Code Playgroud)

第一个孩子班:

public class ChildOne : ParentClass {
    public new void foo() {
        Debug.Log("Child one called!");
    }
}
Run Code Online (Sandbox Code Playgroud)

第二个孩子班:

public class ChildTwo : ParentClass {
    public new void foo() {
        Debug.Log("Child two called!");
    }
}
Run Code Online (Sandbox Code Playgroud)

在第四个类中,我有一个包含多个ChildOne和ChildTwo对象的ArrayList.ArrayList不包含任何其他类型的对象.

如何访问子对象的foo()函数?

public class Example {
    public void someFunction() {
        //...

        ArrayList children = new ArrayList();
        children.add(new ChildOne());
        children.add(new ChildTwo());

        children[0].foo(); //here I want to call the foo() function of the ChildOne object
        children[1].foo(); //here I want to call the foo() function of the ChildTwo object

        //...
    }
}
Run Code Online (Sandbox Code Playgroud)

转换为ParentClass不起作用,我不能转换为其中一个子类,因为我不知道每个元素的类型.

Kin*_*tic 6

如果可以,您可以使用多态而不是隐藏父级的foo函数.

为了实现这个结果,我们可以转换父类以使foo方法成为虚拟,因此我们可以在子类中覆盖它:

public class ParentClass {
    public virtual void foo() {
        Debug.Log("Parent called!");
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在少儿班,我们更换的关键字覆盖关键字:

public class ChildOne : ParentClass {
    public override void foo() {
        Debug.Log("Child one called!");
    }
}

public class ChildTwo : ParentClass {
    public override void foo() {
        Debug.Log("Child two called!");
    }
}
Run Code Online (Sandbox Code Playgroud)

使用ArrayList,您可以这样调用foo方法:

ArrayList children = new ArrayList();
children.Add(new ChildOne());
(children[0] as ParentClass).foo(); // will display "Child one called!"
Run Code Online (Sandbox Code Playgroud)

请注意,children [0]返回一个对象.您必须将此对象强制转换为ParentClass才能调用foo方法.

我的最后一个建议是使用List而不是ArrayList.列表是强类型的(您不必投射任何东西)并且因为没有装箱/拆箱而快一点.现在使用ArrayList的原因并不多(如果有的话).

var children = new List<ParentClass>();
children.Add(new ChildOne());
children[0].foo(); // will display "Child one called!"
Run Code Online (Sandbox Code Playgroud)