[英]Adding a new parameter to constructor on the base class means I have to refactor all of the classes that inherit from it?
[英]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();
编辑:如果基础 class ( Vehicle
)没有任何public
或protected
的构造函数(但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.