繁体   English   中英

如何使用委托调用样式方法?

[英]How can I use delegates to call styling methods?

我需要使用iTextSharp在PDF中设置大量不同元素的样式(阅读:“单元”)。 标签,标题,子标题,数字等。现在,我对每种单元格类型使用三种不同的方法:

public static PdfPCell GetDefaultCell(string strText)
    {
        PdfPCell cell = new PdfPCell(new Phrase(strText, GetDefaultFont()));
        cell.Border = 0;
        return cell;
    }

public static PdfPCell GetDefaultCell(string strText, int iColspan)
    {
        PdfPCell cell = new PdfPCell(new Phrase(strText, GetDefaultFont()));
        cell.Border = 0;
        cell.Colspan = iColspan;
        return cell;
    }

public static PdfPCell GetDefaultCell(string strText, int iColspan, int iAlign)
    {
        PdfPCell cell = new PdfPCell(new Phrase(strText, GetDefaultFont()));
        cell.Border = 0;
        cell.Colspan = iColspan;
        cell.HorizontalAlignment = iAlign;
        return cell;
    }

其中,“默认”用三种方法的每组的单元格类型替换。 我认为这没有规模。 尤其是当我最终使用的类型超过20或30时。 如果我不仅要修改colspan和horizo​​ntalalignment属性,该怎么办? 我可以在这里使用代表吗? 我的方法调用中唯一的区别是方法中的名称和GetXFont()调用。

您可以将委托传递给返回字体的方法:

public static PdfPCell GetCell(string strText, Func<Font> fontCreator)
{
    PdfPCell cell = new PdfPCell(new Phrase(strText, fontCreator()));
    cell.Border = 0;
    return cell;
}

var cell = GetCell("...", () => GetDefaultFont());

但是,为什么不直接将字体直接传递给方法呢?

public static PdfPCell GetCell(string strText, Font font)
{
    PdfPCell cell = new PdfPCell(new Phrase(strText, font));
    cell.Border = 0;
    return cell;
}

var cell = GetCell("...", GetDefaultFont());

您当然可以在您的情况下使用委托,但问题是它是否确实必要。 如果函数GetDefaultFont返回要在单元格中使用的字体,则可以简单地将此字体作为另一个参数传递(即,将调用它的责任交给GetXXXCell方法的调用者)。 在这里传递委托似乎是不必要的抽象。

暂无
暂无

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

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