【问题标题】:how to make an instance of a subclass of type base class C#如何创建类型基类 C# 的子类的实例
【发布时间】:2017-04-10 02:34:09
【问题描述】:

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

Vehicle m=new Motorcycle();

我可以访问 Vehicle 类的所有属性,但看不到 Motorcycle 类的属性。 谢谢

【问题讨论】:

  • 好吧,要么不将其声明为Vehicle,而是将其声明为Motorcycle,或者将其转换为Motorcycle,您需要在此处访问此类型的属性或方法。

标签: c# inheritance subclass abstract superclass


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多