c#中抽象class中的私有构造函数有什么用?

What is the use of private constructor in abstract class in c#?

我在面试中遇到了以下问题。

Q1.Can we have a private constructor in the abstract class?

A​​nswer- 是的,我给了一个答案,我们可以有然后他又问为什么以及私有构造函数的用途是什么。 我无法回答这个交叉问题。有人可以解释一下吗?实际上在 c# 中会有很大帮助。

我能想到两种用途:

首先,用于链接。您可能有多个受保护的构造函数,但想在所有构造函数中执行公共代码:

public abstract class Foo
{
    protected Foo(string name) : this(name, 0)
    {
    }

    protected Foo(int value) : this("", value)
    {
    }

    private Foo(string name, int value)
    {
        // Do common things with name and value, maybe format them, etc
    }
}

第二个用途是使唯一可能派生的 classes 成为 nested classes,它们可以访问 private成员。当我想强制执行有限数量的派生 classes 时,我曾经使用过它,实例通常通过基础 class

公开
public abstract class Operation
{
    public static readonly Operation Add { get; } = new AddOperation();
    public static readonly Operation Subtract { get; } = new SubtractOperation();

    // Only nested classes can use this...
    private Operation()
    {
    }

    private class AddOperation : Operation
    {
        ...
    }

    private class SubtractOperation : Operation
    {
        ...
    }
}