从超类 C# 访问子类方法

某人_

所以我知道我实际上无法从它的父类访问子类的方法和属性。但是我有一个程序将 Vehicles 存储在一个数组中(不是 arraylist - 它的作业)。Vehicles 然后初始化为 Airplane、Boat 或从 Vehicle 类派生的 Car 对象。这些子类具有独特的属性,我想知道如何访问这些子类?

这是一些(简化的)相关代码:

Vehicle[] vehicles = new Vehicle[20];

vehicles[0] = new Airplane();

// Setting an attribute of the superclass
vehicles[0].Make = "Boeing";

// Set an attribute from the Airplane class
vehicles[0].Engine = "Jet"; //(obviously this doesn't work)

我该如何解决这个问题?我已经研究了几个小时,但我被这个问题难住了。

谢谢 :)

编码器

您可以通过引用的声明类型来访问引用。因为您将数组声明为 of Vehicle,所以您不能直接访问子类成员。

为此,将对象与包含它的集合分开初始化:

var jet = new Airplane();
jet.Make = "Boeing";
jet.Engine = "Jet";

vehicles[0] = jet;

或者,使用对象初始值设定项:

vehicles[0] = new Airplane
{
    Make = "Boeing",
    Engine = "Jet"
};

在实例化后立即将其回滚是非常荒谬的,但您也可以这样做:

vehicles[0] = new Airplane();
((Airplane)vehicles[0]).Make = "Boeing";
((Airplane)vehicles[0]).Engine = "Jet";

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章