C# 初始值设定项在转换 VB 的 With/End With 语句中的用法



我正在将Word VBA宏转换为C#,这是我正在编写的插件的一部分。

我研究了将With/End With VB块转换为C#的选项。然后我继续尝试转换我的VBA PageSetup设置:

With ActiveDocument.PageSetup
    .Orientation = wdOrientPortrait
    .TopMargin = InchesToPoints(0.98)
    .BottomMargin = InchesToPoints(0.98)
    .LeftMargin = InchesToPoints(0.92)
    .RightMargin = InchesToPoints(0.92)
    .Gutter = InchesToPoints(0)
    .HeaderDistance = InchesToPoints(0.49)
    .FooterDistance = InchesToPoints(0.49)
    .PageWidth = InchesToPoints(8.5)
    .PageHeight = InchesToPoints(11)
    .LayoutMode = wdLayoutModeDefault
End With

因此,使用@JohnKeet对这个问题的回答,我写了我的C#代码:

var oPageSetup = new Word.PageSetup
{
    Orientation = Word.WdOrientation.wdOrientPortrait,
    TopMargin = (float)(0.98 * 72),
    BottomMargin = (float)(0.98 * 72),
    LeftMargin = (float)(0.92 * 72),
    RightMargin = (float)(0.92 * 72),
    Gutter = (float)(0),
    HeaderDistance = (float)(0.49 * 72),
    FooterDistance = (float)(0.49 * 72),
    PageWidth = (float)(8.5 * 72),
    PageHeight = (float)(11 * 72),
    LayoutMode = Word.WdLayoutMode.wdLayoutModeDefault
};

然而,在这样做的时候,我得到了以下编译器错误:

无法创建抽象类或接口"Microsoft.Office.Interop.Word.PageSetup"的实例

有人能就我做错了什么以及如何更正代码向我提供建议吗?提前谢谢。

With ActiveDocument.PageSetup不会创建PageSetup的实例。它使用名为PageSetupActiveDocument的属性。因为没有对象实例化,所以不能使用Jon Skeet所指的对象初始化器语法。相反,每次都必须重复变量名:

var ps = ActiveDocument.PageSetup;
ps.Orientation = Word.WdOrientation.wdOrientPortrait;
ps.TopMargin = (float)(0.98 * 72);
ps.BottomMargin = (float)(0.98 * 72);
ps.LeftMargin = (float)(0.92 * 72);

最新更新