【发布时间】:2018-11-13 02:32:14
【问题描述】:
Book类继承抽象类Goods。 Book 方法与 Goods 方法具有相同的参数。而且还有numPages,这是为什么呢?
public Book(string title, string barCode, double price, int numPages)
如果我有一个类继承 Book 类,我是否必须将所有相同的参数都放入并创建一个新的?
public Author(string title, string barCode, double price, int numPages, string author)
我希望这有任何意义。
abstract class Goods
{
public decimal weight;
string Title, BarCode;
double Price;
public Goods(string title, string barCode, double price)
{
Title = title;
BarCode = barCode;
Price = price;
}
}
abstract class Book : Goods
{
protected int NumPages;
public Book(string title, string barCode, double price, int numPages)
: base(title, barCode, price)
{
NumPages = numPages;
weight = 1;
}
【问题讨论】:
-
Do you have to add a variable to a method that has :base?否。您可以通过删除NumPages并验证它是否仍然有效来自行测试。 -
具有
:base"的"方法是一个构造函数。不,您没有必须向其中添加任何变量。但是我不清楚如果你想在子类的构造函数列表中添加一个变量,是否必须复制原始构造函数。 “向其中添加变量”是什么意思?换句话说,添加新属性(或在您的情况下为受保护的字段)而不在构造函数中为其添加初始化程序是非常好的。 -
这个问题不太清楚。但是当涉及到抽象类时,如果你试图做一些你不能做的事情或不做你必须做的事情,编译器会给你一个错误。因此,如果问题是您必须做什么,这是一个简单的判断方法。或者你在问你应该怎么做?
标签: c# variables inheritance abstract base