代码之家  ›  专栏  ›  技术社区  ›  Robert Massa

我可以给一个抽象类加上一个子类吗?(C)

  •  1
  • Robert Massa  · 技术社区  · 16 年前

    假设我想设计一个抽象系统来计算文档中的节数。我设计了两个课程, 文件 截面 ,文档有一个节列表和一个计算节数的方法。

    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;
    }
    

    现在,我希望能够在多个场景中使用此代码。例如,我有带章节的书。这本书将是文件的一个子类,而第章是章节的一个子类。这两个类都将包含额外的字段和功能,与节的计数无关。

    我现在遇到的问题是,由于文档中包含章节,而不是章节,所以添加的章节功能对我来说是无用的,只能添加 作为一个 要预订的分区。

    我曾经读过有关“低调”的文章,但我真的认为这不是正确的选择。我在想也许我完全采取了错误的方法。

    我的问题是:我如何设计这样一个抽象系统,它可以被子类对象重用,这是一种可行的方法吗?

    1 回复  |  直到 16 年前
        1
  •  6
  •   Jon Skeet    16 年前

    你需要仿制药:

    public abstract class Document<T> where T : Section
    
    public abstract class Section
    
    public class Book : Document<Chapter>
    
    public class Chapter : Section
    

    你可能 想让一个部分知道它可以是什么类型的文档的一部分。不幸的是,这变得更加复杂:

    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>
    

    我必须在协议缓冲区中这样做,这很混乱——但它允许您以强类型的方式引用这两种方式。如果你能逃脱的话,我会选第一版的。