我可以子类化一个抽象类,它有另一个也是子类的抽象类吗?(C#)

Rob*_*ssa 1 c# oop

让我们说我想设计一个抽象系统来计算文档中的部分.我设计了两个类,DocumentSection,该文档有一个部分列表和一个计算它们的方法.

public abstract class Document {
  List<Section> sections;

  public void addSection(Section section) { 
    sections.Add(section);
  }
  public int sectionCount() { 
    return sections.count;
  } 
}
public abstract class Section {
  public string Text;
}
Run Code Online (Sandbox Code Playgroud)

现在,我希望能够在多重场景中使用此代码.例如,我有章节书籍.本书将是Document的子类,而Chapter是Section的子类.这两个类都将包含额外的字段和功能,与计数部分无关.

我偶然遇到的问题是因为Document包含部分而不是Chapters,章节的附加功能对我来说是无用的,它只能作为 Book 一部分添加.

我正在阅读有关向下倾斜的内容,但我认为这不是正确的方法.我想也许我完全采取了错误的做法.

我的问题是:如何设计这样一个抽象系统,可以被子类化对象重用,这是要走的路吗?

Jon*_*eet 6

你需要泛型:

public abstract class Document<T> where T : Section

public abstract class Section

public class Book : Document<Chapter>

public class Chapter : Section
Run Code Online (Sandbox Code Playgroud)

您可能想让一个部分知道它可以属于哪种文档.不幸的是,这变得更加复杂:

public abstract class Document<TDocument, TSection>
    where TDocument : Document<TDocument, TSection>
    where TSection : Section<TDocument, TSection>

public abstract class Section<TDocument, TSection>
    where TDocument : Document<TDocument, TSection>
    where TSection : Section<TDocument, TSection>

public class Book : Document<Book, Chapter>

public class Chapter : Section<Book, Chapter>
Run Code Online (Sandbox Code Playgroud)

我必须在Protocol Buffers中执行此操作,并且它很混乱 - 但它确实允许您以强类型方式引用这两种方式.如果你能逃脱它我会去第一个版本.