0

我有一个包含我们所有校友杂志的 xml 文档。

<Magazine>
  <Volumes>
    <Volume>
      <Issues>
        <Issue>
          <Sections>
            <Section>
              <Articles>
                <Article>
                  <Images>
                    <Image>
                    </Image>
                    ...
                  </Images>
                </Article>
                ...
              </Articles>
            </Section>
            ...
          </Sections>
        </Issue>
        ...
      </Issues>
    </Volume>
    ...
  </Volumes>
</Magazine>

我为:Volume、Issue、Section、Article 和 Image 创建了一个类。

我的问题是:
我应该创建一个超类和子类的层次结构吗?
即——图像继承文章继承部分继承问题继承卷
或者
我是否将它们分开并使用通用集合作为父类的属性?
即——Volume.Issues、Issue.Sections、Section.Articles、Article.Images

其他我完全不知道的东西?

这些选择的优点/缺点/缺点是什么?

编辑:如果我使用的是问题对象,我还需要知道卷号和卷年,以及每个部分中的文章标题。

4

3 回答 3

0

如果所有类都具有共同的属性/方法,则可以使用继承,否则继承将毫无意义。

您可以使用Linq To XML从 xml 文档中获取所需的所有数据,而无需将其映射到类,或Linq to Object在映射后使用

于 2012-05-17T15:29:04.513 回答
0

对于您的情况,继承听起来完全错误。仅当域类之间存在自然的层次关系时才应使用它。一个经典的例子是

-Employee 
--Contractor
--Permanent

他们仍然需要姓名、地址和类似的方法,例如:hire()、fire()、pay()。

在您的情况下,继承没有关系,这是一个经典示例,说明为什么您应该支持组合而不是继承

图片不是文章,但文章有图片。这可以应用于您的整个结构。

一切都是关于“有一个”而不是“是一个”。

于 2012-05-17T15:35:57.447 回答
0

确切的答案是只有当您知道您打算如何在应用程序中使用这些数据、如何存储数据、如何显示等时才知道。

通常,文章是一个有用的起点类(类似于博客文章等)。您不需要杂志内的文章(而不是 MagazineIssue)

    //search all articles in some Magazine issue
    public IList<Article> GetArticles(long ISBN, string issueNumber)
    {
        //implementation
    }

在某些情况下,您也不需要 Section 类。

public class Article
{
    //can be immutable
    public MagazineIssueView Issue { get; set; }

    public string Author { get; set; }

    public IList<Section> Sections { get; set; }

    public IList<Image> GetAllArticleImages()
    {
        return Sections
            .SelectMany<Section, ContentBlock>(s => s.SectionContent)
            .Where(c => c is Image)
            .Cast<Image>()
            .ToList();
    }
}

public class MagazineIssueView
{
    public long ISBN { get; set; }

    //if you have internal Magazines list, it can be also internal MagazineId
    public string MagazineName { get; set; }

    public DateTime IssueDate { get; set; }

    public string IssueNumber { get; set; }
}

public class Section
{
    public string SectionTitle { get; set; }
    public int Order { get; set; }

    public IList<ContentBlock> SectionContent { get; set; }
}

public abstract class ContentBlock
{
}

public class Image: ContentBlock
{
}

public class Paragraph: ContentBlock
{
}
于 2012-05-17T15:39:58.363 回答