如何组织重复代码?

时间:2016-05-31 13:35:35

标签: c#

代码如下:

1)我有一些图片:

var imageIds = caseStudyPage.Images;
foreach (var imageId in imageIds)
{
    byte[] csImage = GetImage(imageId);
}

2)我的结构如下:

var document = new Document();
document
    .AddField(new TextField("CS Counter Basic Name", "Case Study"))
    .AddField(new TextField("CS Counter Number", _numberInParentDocument.ToString()))
    .AddField(new TextField("Page Title", caseStudyPage.Page_Title))
    .AddField(new TextField("Common Footer Text 1", commonFooterText1))
    .AddField(new TextField("Page Title Content", caseStudyPage.Page_Title))
    .AddTable(new Table("Images")
        .AddRow(new TableRow().AddField(new ImageField("Image", imageBytes, ImageType.Jpeg))
            .AddField(new TextField("Overview", caseStudyPage.Overview))
            .AddField(new TextField("Engagement", caseStudyPage.Engagement))
            .AddField(new TextField("Publish Date", caseStudyPage.Publish_Date.ToString("MMM. dd, yyyy")))
    .AddField(new TextField("Common Footer Text 2", commonFooterText2))));

我需要将来自2)的文档结构放在1)的循环中,以便设置ImageField的imageBytes变量,但是文档应该只有一个。我不知道如何只循环这部分:

.AddRow(new TableRow().AddField(new ImageField("Image", imageBytes, ImageType.Jpeg))

1 个答案:

答案 0 :(得分:0)

var document = new Document();
document
    .AddField(new TextField("CS Counter Basic Name", "Case Study"))
    .AddField(new TextField("CS Counter Number", _numberInParentDocument.ToString()))
    .AddField(new TextField("Page Title", caseStudyPage.Page_Title))
    .AddField(new TextField("Common Footer Text 1", commonFooterText1))
    .AddField(new TextField("Page Title Content", caseStudyPage.Page_Title));

var table = new Table("Images");
foreach (var imageId in imageIds)
{
    byte[] csImage = GetImage(imageId);
    table.AddRow(new TableRow().AddField(new ImageField("Image", csImage, ImageType.Jpeg))
            .AddField(new TextField("Overview", caseStudyPage.Overview))
            .AddField(new TextField("Engagement", caseStudyPage.Engagement))
            .AddField(new TextField("Publish Date", caseStudyPage.Publish_Date.ToString("MMM. dd, yyyy")));
}

document.AddTable(table);
document.AddField(new TextField("Common Footer Text 2", commonFooterText2))));