在 C# 中使用抽象 类 中的静态方法是新的吗?

Is the use of static methods in abstract classes new in C#?

在 GitHub 浏览 Roslyn 源代码时,我遇到了 CSharpSyntaxTree,它是一个带有静态方法的 public 抽象 class。我以前没见过这个,想知道这是否是一种新趋势。

在阅读上述 class 的代码时,我的第一反应是 "Oh OK, this is an interface definition." 但是随后,看到以下静态方法时感到困惑:

    /// <summary>
    /// Produces a syntax tree by parsing the source text.
    /// </summary>
    public static SyntaxTree ParseText(
        SourceText text,
        CSharpParseOptions options = null,
        string path = "",
        CancellationToken cancellationToken = default(CancellationToken))
    {
        if (text == null)
        ...
    }

此外,这个 SO question and an answer 表明抽象 class 中的静态方法不是好的做法。如果是这样,为什么微软的相对现代的源代码会延续这种做法?

我的背景是C++,感觉C++复杂的没必要。我不想看到同样的事情发生在 C# 上。

Is the use of static methods in abstract classes new in C#?

没有

Why would relatively modern source code from Microsoft perpetuate such a practice?

上下文就是一切。在这种情况下,很明显 CSharpSyntaxTree.ParseText 是一个工厂方法——它 returns 一个新的 ParsedSyntaxTree 实例(它是 CSharpSyntaxTree 的私有子 class)。这是对抽象 class.

静态方法的完全有效使用

我什至会更进一步,不同意您链接的答案。抽象基 classes 通常只是为了方便,以减少代码重复并从其子classes 中捕获一些常见行为。在这种情况下,将常见的静态方法放在上面是有意义的。

不,这不是新功能。 您可以在此处查看对 C# 所做的更改
https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-version-history

在抽象 classes 上允许静态方法并不新鲜,从来没有任何禁止它们的特殊规则。

我不同意这是不好的做法。如果静态方法与静态方法所涉及的概念相关,那么这是放置它的好地方。例如,它通常对工厂方法有意义。

My first reaction while reading the code for the said class was "Oh OK, this is an interface definition."

如果只定义一个接口,没有任何功能,通常在 C# 中使用 interface 比抽象 class 更好。