简体   繁体   中英

C# How to access inherited object from parent List

I'm trying to find a way to make a list of parent object with a variety of inherited objects. Here is an example.

class Prog {
    public Prog ( ) {
        List<Shape> shapes = new List<Shape>();
        shapes.Add( new Cube() );
        shapes.Add( new Shape() );

        //All those ways will not work, I cannot figure a way how to do this
        shapes[0].CubeFunction(); 
        (Cube)shapes[0].CubeFunction();
        Cube cube = shapes[0];
    }
}

class Shape {
    public Shape (){}
}

class Cube : Shape {        
    public Cube (){}
    public void CubeFunction(){}
}

Does anyone know how to get the code in class Prog to work?

Your cast version is nearly right - it's only wrong because of precedence. You'd need:

((Cube)shapes[0]).CubeFunction();

Alternatively:

Cube cube = (Cube) shapes[0];
cube.CubeFunction();

The need to cast like this is generally a bit of a design smell, mind you - if you can avoid it, it's worth trying to do so.

If you are not sure the cast is valid and don't want an InvalidCastException to be thrown, you can do like this:

Cube cube = shapes[0] as Cube;
if (cube == null)
{
    // cast is not valid
}
else
{
    cube.CubeFunction();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM