如何创建 subclass 类型 base class C# 的实例

how to make an instance of a subclass of type base class C#

我创建了一个名为 Vehicle 的抽象 class 并且有 2 个子 classes:摩托车和汽车。 如何使用 Vehicle 类型创建 Motorcycle 实例? 所以像这样:

Vehicle m=new Motorcycle();

我可以访问车辆 class 的所有属性,但看不到摩托车 class 的属性。 谢谢

Motorcycle 的一个实例 被视为 Vehicle,那么它很自然地无法让您访问 Motorcycle的独特属性。这就是继承的意义。

要访问它们,您必须 type-cast the instance:

Vehicle v = new Motorcycle();
((Motorcycle)v).MotorbikeEngineVolume = 250;

当您不能确定实例确实是 Motorcycle 时,请使用 is operator:

Vehile v = …
…
if (v is Motorcycle) 
{
    ((Motorcycle)v).MotorbikeEngineVolume = 250;
}

通过编写上面的语句,您将只能访问那些从 Vehicle 继承或在 Motorcycle 中被覆盖的 Motorcycle 成员,但是如果您想访问那些不属于 Vehicle 的 Motorcycle 成员,则您必须写: 摩托车 m=new Motorcycle(); 通过使用此实例,您将能够访问 derived class 的成员。 谢谢!