简体   繁体   中英

How can I use delegates to call styling methods?

I need to style a ton of different elements (read: "cells") in a PDF using iTextSharp. Label, header, subheader, number, etc. Right now, I'm using three different methods for each cell type:

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

Where "Default" is substituted with the cell type for each set of three methods. I don't think this scales. Especially if I end up with more than the 20 or 30 types I have now. What if I want to modify more than just the colspan and horizontalalignment attributes? Can I use delegates here ? The only difference in my method calls is the name and the GetXFont() call within the method.

You can pass a delegate to the method which returns the font:

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());

But why don't you simply pass the font directly to the method?

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());

You can certainly use delegates in your situation but the question is if it's really necessary. If the function GetDefaultFont returns a font that you want to use in your cell, you can simply pass this font as another argument (ie put the responsibility of calling it to the caller of your GetXXXCell method). Passing a delegate seems like an unnecessary abstraction here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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