【发布时间】:2014-07-12 02:08:33
【问题描述】:
将继承的类构造函数的参数传递给到基类构造函数的“C#方式”是什么?这是否需要我覆盖基类中的 base_model 字符串?
// Base class
class vehicle
{
private string base_model = String.Empty;
vehicle(string model)
{
this.base_model = model;
}
}
// Inherited classes
class tesla : vehicle
{
private readonly string model = "Model S"; // This is unchanging
tesla(string model) : base ( **pass model to base_model** )
{
// Initialize
}
}
class ferrari : vehicle
{
private readonly string model = "458 Spider"; // This is unchanging
ferrari(string model) : base ( **pass model to base_model** )
{
// Initialize
}
}
编辑
@JohnLBevan 引起了我的注意:
这让人想起另一个问题:tesla 类(或ferrari 类)是否可以没有构造函数参数并自动将model 变量(即"Model S")传递给base_model?
【问题讨论】:
-
IMO 实际模型实例名称不属于基础。它属于实例。
-
@MitchWheat 你能提供一些代码作为例子吗?不知道如何应用。
-
我支持comment from Mitch - 你所做的很糟糕 - 基类不应该知道任何关于扩展(派生)类的信息。
标签: c# inheritance constructor