简体   繁体   English

C#如何从父级列表访问继承的对象

[英]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? 有谁知道如何使Prog类中的代码正常工作?

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: 如果不确定类型转换是否有效并且不希望引发InvalidCastException ,则可以执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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