【问题标题】:Creating a new object and calling the method at the same time创建新对象并同时调用方法
【发布时间】:2021-12-21 02:42:20
【问题描述】:

我有简单的代码(iTextShar 库)用 Phrase 生成 PdfCell:

//I create new Phrase
Phrase p = new("Lorem ipsum", myFont);

//I set leading for Phrase
p.setFixedLeading(10f);

//I create new Table Cell end insert Phrase
PdfPCell cell = new(p);

为什么我不能直接在 PdfPCell 上生成 Phrase 并同时运行方法 .setFixedLeading。有这样的想法吗?

PdfPCell cell = new(Phrase p("Lorem ipsum", myFont).setFixedLeading(10f));

在创建新的 Phrase 对象时,有没有办法使用 .setFixedLeading 方法设置Leading?

【问题讨论】:

  • 你不能这样做,因为setFixedLeading 不会返回任何东西。有没有类似于WithFixedLeading 的方法返回this,你可以。这被称为流畅的界面。如果FixedLeading 是一个属性,您还可以使用对象初始化器形式的一个表达式 (new Phrase("Lorem ipsum", myFont) { FixedLeading = 10f })。

标签: c# oop


【解决方案1】:

您可以编写自己的方法:

private Phrase CreatePhraseWithFixedLeading(string text, Font font, float fixedLeading)
{
   Phrase p = new(text, font);
   p.setFixedLeading(fixedLeading);
   return p;
}

用法是

Phrase p = CreatePhraseWithFixedLeading("lorem ipsum", myFont, 10f);
PdfPCell cell = new(p);

或者,如果您在创建单元格后不需要该短语

PdfPCell cell = new(CreatePhraseWithFixedLeading("lorem ipsum", myFont, 10f));

如果您在创建短语后有更多方法可以调用,您可以查看构建器模式。

但另一方面,你应该问问你从中获得了什么。您提供的代码非常好。不要试图将尽可能多的内容放在一行中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-28
    • 1970-01-01
    • 1970-01-01
    • 2013-05-11
    • 2014-10-08
    相关资源
    最近更新 更多