Domanda

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?

È stato utile?

Soluzione

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.

Altri suggerimenti

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();
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top