简体   繁体   English

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

[英]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. 我需要使用iTextSharp在PDF中设置大量不同元素的样式(阅读:“单元”)。 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. 尤其是当我最终使用的类型超过20或30时。 What if I want to modify more than just the colspan and horizontalalignment attributes? 如果我不仅要修改colspan和horizo​​ntalalignment属性,该怎么办? Can I use delegates here ? 我可以在这里使用代表吗? The only difference in my method calls is the name and the GetXFont() call within the method. 我的方法调用中唯一的区别是方法中的名称和GetXFont()调用。

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). 如果函数GetDefaultFont返回要在单元格中使用的字体,则可以简单地将此字体作为另一个参数传递(即,将调用它的责任交给GetXXXCell方法的调用者)。 Passing a delegate seems like an unnecessary abstraction here. 在这里传递委托似乎是不必要的抽象。

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

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