CS0426 创建对象时 - 如何理解错误

CS0426 when creating an object - How to understand error

尝试使用 DocumentFormat.OpenXml.Packaging 命名空间中的 SpreadsheetDocument class 打开 Excel 时出现 CS0426 编译器错误。

我意识到这是因为我使用的是 new,并且出于某种原因,编译器不喜欢它。

为什么我不能使用 new 创建对象的实例?

//Error CS0426
using (SpreadsheetDocument goldenFile = new SpreadsheetDocument.Open(goldenPath, true));

//Ok code
using (SpreadsheetDocument goldenFile = SpreadsheetDocument.Open(goldenPath, true));

它不起作用,因为按原样,当您使用 new 时,您实际上是在告诉您的代码 - "Create an object of a nested class 'Open'"。 摆脱 new 或实现 public 构造函数,然后调用静态 Open 方法。

Open 方法是一个静态方法,它在其实现中使用 new 并且 returns 是 SpreadsheetDocument 的一个实例。这就是您不需要使用 new 的原因。参考documentation.

根据其名称和上下文判断,SpreadsheetDocument.Open 方法会为您打开一个新的电子表格文件 read/write from/to.

这应该是正确的使用方法 API:

using (SpreadsheetDocument goldenFile = SpreadsheetDocument.Open(goldenPath, true)) {
    ...
}

你要明白并不是每一个class都需要你写new这个词然后直接调用构造函数来创建。有时,例如在这种情况下,SpreadsheetDocument 的实例可能是在 Open 方法内部的某处创建的。 Open 方法简单地 returns 新实例,以便您可以将其分配给变量(在本例中为 goldenFile)。

您也可以编写一个使用静态方法创建的 class:

class Foo {
    // properties...

    // private constructor
    private Foo() { ... }

    public static GiveMeAFoo() {
        return new Foo();
    }
}

我现在可以创建 Foo 的实例而无需直接使用 new:

var foo = Foo.GiveMeAFoo();

Open 内部发生了类似的事情。


编译器给出错误 CS0426,因为它是这样认为的:

I see that you are using the new operator, so you are creating a new instance of a type. What type is it that you are creating? Let's see... It's SpreadsheetDocument.Open! But wait a minute! That's not a type! I can't find a type called Open in SpreadsheetDocument!

因此出现错误:

The type name 'Open' does not exist in the type 'SpreadsheetDocument'.