繁体   English   中英

如果基础 class 没有构造函数,我可以从 class 继承吗

[英]Can I inherit from a class if base class doesn't have constructor

所以我有一辆没有构造函数的Vehicle class 。 我想制作一个名为VehicleExtended的新 class ,它继承Vehicle 错误是:

'Vehicle' 不包含采用 0 arguments (CS1729) 的构造函数

是否可以在没有构造函数的情况下继承?

注意:我无法编辑基础 class 因为我只能看到它的元数据。

public class VehicleData : Vehicle
{
    [BsonId]public int _id { get; private set;}
    public bool IsCompany { get; private set;}
    public int OwnerID { get; private set; }
    public string modelName { get; private set;}
}

正如我们从错误消息中看到的,基础 class Vehicle没有没有 arguments的构造函数:

  public class Vehicle { 
    ...
    // every Vehicle constructors want some parameters, e.g. id and ownerId
    public Vehicle(int id, int ownerId) {...}
    ...
  }

那是编译器不知道如何创建VehicleData的实例:

  // Since VehicleData is inherited from Vehicle, 
  // Vehicle cosntructor should be executed.
  // What arguments should be passed to it?   
  var test = new VehicleData();

您必须手动实现VehicleData构造函数,您应该在其中指定 arguments:

  public class VehicleData : Vehicle 
  {
    // When creating an instace, use -1 and -1 when calling base constructor
    public VehicleData() : base(-1, -1) {}

    ...
  }

现在上面的代码是合法的:

  // We don't want parameters when creating VehicleData instance
  // When creating base class (Vehicle) -1 and -1 are used  
  var test = new VehicleData();

编辑:如果基础 classVehicle没有任何publicprotected的构造函数(但private构造函数),则您不能从VehicleData创建基础Vehicle实例,因此不能从Vehicle继承。 private构造函数只是一个旧的C++技巧; C#的情况下,为了防止继承,我们应该使用sealed

基础 class 可能有一个无法访问的私有构造函数。 在这种情况下,您不能继承 class。

根据错误消息,我假设 class VehicleData具有私有零参数构造函数。 在这种情况下,您不能从VehicleData继承。 例如

public class A
{
    private A() {}
}
public class B : A
{
}

这不会编译。 但是,如果有一个公共或受保护的非 zeor 参数列表,您可以从 class 继承:

public class A
{
    private A() {}
    public A(int i) {}
}
public class B : A
{
    public B() : base(0) {}
}

此外,如果事实证明Vehicle只有private构造函数,并且您只想添加特定行为而不是任何无法从已经在Vehicle中定义的属性计算的属性,而不是继承,您可以使用扩展方法。

public static VehicleExtesnion
{
    public SomeType DoStuff(this Vehicle vehicle) 
    {
        // do stuff with vehicle
    }
}

暂无
暂无

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

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