简体   繁体   English

从非抽象类派生抽象类

[英]Derive abstract class from non-abstract class

Is it OK to derive an abstract class from a non-abstract class or is there something wrong with this approach? 从非抽象类派生抽象类是否可以,或者这种方法有问题吗?

Here´sa little example: 这是一个小例子:

public class Task {
  // Some Members
}

public abstract class PeriodicalTask : Task {
  // Represents a base class for task that has to be done periodicaly.
  // Some additional Members
}

public class DailyTask : PeriodicalTask {
  // Represents a Task that has to be done daily.
  // Some additional Members
}

public class WeeklyTask : PeriodicalTask {
  // Represents a Task that has to be done weekly.
  // Some additional Members
}

In the example above I do not want to make the class Task abstract, because I want to instantiate it directly. 在上面的例子中,我不想让类Task抽象,因为我想直接实例化它。 PeriodicalTask should inherit the functionality from Task and add some additional members but I do not want to instantiate it directly. PeriodicalTask​​应该从Task继承功能并添加一些额外的成员,但我不想直接实例化它。 Only derived class of PeriodicalTask should be instantiated. 只应实例化PeriodicalTask​​的派生类。

I don't see anything wrong with this approach. 我认为这种方法没有任何问题。

You might have some basic type that can be described in concrete terms. 您可能有一些可以用具体术语描述的基本类型。 Now, just because an object of this type might be further classified according to some subtype, it does not follow that all such subtypes are just as concrete; 现在,仅仅因为这种类型的对象可能会根据某个子类型进一步分类,并不是说所有这些子类型都具体; they may in turn require further concretization, as it were. 他们可能反过来要求进一步具体化。

Real-world example: 现实世界的例子:

Person -- concrete (non-abstract) Person - 具体 (非抽象)
Sibling: Person -- abstract Sibling: Person - 抽象
Brother: Sibling -- concrete Brother: Sibling - 混凝土
Sister: Sibling -- concrete Sister: Sibling - 混凝土

Nothing wrong with it. 它没有错。

If you look at a big hierarchy like WinForms, you will find several layers of abstract types. 如果你看一下像WinForms这样的大层次结构,你会发现几层抽象类型。

MSBuild tasks are also a good (and more relevant) example. MSBuild任务也是一个很好的(更相关)的例子。

This sort of thing happens all the time: All abstract classes inherit from System.Object , a class that is not abstract by itself. 这种事情一直在发生:所有抽象类都继承自System.Object ,这个类本身并不是abstract的。

new System.Object() is sometimes useful for locking, if you don't have anything else around, you could lock over. new System.Object()有时用于锁定,如果你没有其他任何东西,你可以锁定。

Using abstract is not the right approach here then, use a protected or internal constructor, for example. 因此,使用抽象不是正确的方法,例如,使用受保护的或内部构造函数。 That would prevent instances of PeriodicalTask to be created directly, but its derived classes would still have access to it. 这样可以防止直接创建PeriodicalTask​​的实例,但是派生类仍然可以访问它。

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

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