[英]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和horizontalalignment屬性,該怎么辦? 我可以在這里使用代表嗎? 我的方法調用中唯一的區別是方法中的名稱和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.