简体   繁体   English

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

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

I face the below question in the interview.我在面试中面临以下问题。

Q1.Can we have a private constructor in the abstract class? Q1.抽象类中可以有私有构造函数吗?

Answer- Yes, I gave an answer we can have then he again ask why and what is the use of the private constructor.答案-是的,我给了一个答案,我们可以有那么他再次问为什么,什么是使用私有构造的。 I'm not able to answer to this cross-question.我无法回答这个交叉问题。 Can anybody explain this?有人可以解释一下吗? with practically in c# will great help.实际上在 c# 中会有很大帮助。

I can think of two uses:我可以想到两种用途:

Firstly, for chaining.首先,用于链接。 You might have multiple protected constructors, but want to execute common code in all of them:您可能有多个受保护的构造函数,但希望在所有构造函数中执行通用代码:

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
    }
}

The second use would be to make it so that the only possible derived classes would be nested classes, which have access to private members.第二个用途是使唯一可能的派生类是嵌套类,它们可以访问私有成员。 I've used this before when I want to enforce a limited number of derived classes, with instances usually exposed via the base 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
    {
        ...
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM