在 iText7 的抽象元素上创建扩展方法时遇到问题



我想创建一个扩展方法,既适用于Paragraph对象,也适用于Text对象。这两种类型都有一个共同的祖先AbstractElement。

我想做的是这样的事情:

private static AbstractElement ApplyHeaderStyle(this AbstractElement element)
{
return element.AddStyle(new Style().SetFont(FontFactory.CreateAvenir85Heavy()).SetFontSize(7));
}

这样我就可以在代码中这样称呼它:

new Text("This is some text that I would like as a header").ApplyHeaderStyle();

new Paragraph().Add("This is also text I want in that style").AddHeaderStyle();

我该怎么做?我应该避免将此作为可链接的扩展方法吗?

我通过反复尝试和大量谷歌搜索找到了答案:

private static T HeaderStyle<T>(this T element) where T : AbstractElement<T>
{
return element.AddStyle(CreateHeaderStyle());
}

最新更新