抽象类和只有受保护构造函数的类之间有什么区别?(.净)

Dav*_*son 9 c# constructor abstract-class protected

抽象类和只有受保护构造函数的类之间有什么区别?它们似乎与我非常相似,因为你无法实例化任何一个.

编辑:

如何在派生类中创建实例,并使用带有受保护构造函数的基类?例如:

public class ProtectedConstructor
{
    protected ProtectedConstructor()
    {

    }

    public static ProtectedConstructor GetInstance()
    {
        return new ProtectedConstructor(); // this is fine
    }
}

public class DerivedClass : ProtectedConstructor
{

    public void createInstance()
    {
        ProtectedConstructor p = new ProtectedConstructor(); // doesn't compile
    }

    public static ProtectedConstructor getInstance()
    {
        return new ProtectedConstructor(); // doesn't compile

    }
}
Run Code Online (Sandbox Code Playgroud)

Ray*_*Ray 12

可以在类本身内实例化具有受保护构造函数的类 - 在静态构造函数或静态方法中.这可以用于实现单件或工厂类型的东西.

抽象类根本无法实例化 - 意图是一个或多个子类将完成实现,并且这些类将被实例化

编辑:

如果你打电话ProtectedConstructor.GetInstance();而不是new ProtectedConstructor();,它的确有效.也许受保护的构造函数不能以这种方式调用?但受保护的方法当然可以.

是一篇关于这个主题的有趣文章.