静态类与受保护的构造函数

Ram*_*ran 6 c# static constructor class access-modifiers

我在课堂上收到一条警告消息,例如

在此处输入图片说明

Protected constructor or the在类声明中添加一个static` 关键字

解决方案

在我尝试了以下两种方法后,错误消失了。

static 没有课 constructor

public static class Program    {
    }
Run Code Online (Sandbox Code Playgroud)

使用构造函数的非staticprotected

public  class Program
    {
        protected Program() { }
    }
Run Code Online (Sandbox Code Playgroud)

题:

那么我上面的解决方案中提到的静态类与受保护的构造函数有什么区别?哪一种最好用?

She*_*115 5

static类并不需要一个实例来访问其成员。一个static类不能有实例成员(例如public int MyNumber;,不允许在静态类上使用,因为静态类只允许使用静态成员)。但是,非静态类中允许使用实例成员和静态成员。带有protected构造函数的类只能有一个由它自己创建的实例或从它继承的东西。

public class Program
{
    protected Program()
    {
        // Do something.
    }

    public static Program Create()
    {
        // 100% Allowed.
        return new Program();
    }

    public void DoSomething()
    {

    }
}

public static class AnotherClass
{
    public static Program CreateProgram()
    {
        // Not allowed since Program's constructor is protected.
        return new Program();
    }
}

public class SubProgram : Program
{
    protected SubProgram()
    {
        // Calls Program() then SubProgram().
    }

    public new static Program Create()
    {
        // return new Program(); // We would need to move the SubProgram class INSIDE the Program class in order for this line to work.
        return new SubProgram();
    }
}

Program.Create();               // Can be called since Create is public and static function.
Program.DoSomething()           // Can't be called because an instance has not been instantiated.
var test = Program.Create();
test.DoSomething();             // Can be called since there is now an instance of Program (i.e. 'test').
AnotherClass.CreateProgram();   // Can't be called since Program's constructor is protected.
SubProgram.Create();            // Can be called since SubProgram inherits from Program.
Run Code Online (Sandbox Code Playgroud)

至于性能,这种区别实际上与性能没有太大关系。