为什么我会收到一个"交通不便,由于保护级别和QUOT;错误?我会、不便、级别、错误

2023-09-06 22:31:40 作者:我的爱、只想要你懂

我收到此错误:

CTest.AA()'不可访问由于其保护水平。

'CTest.A.A()' is inaccessible due to its protection level.

编写本code时:

public class A
{
    private A()
    {
    }
}

public class B : A
{
    public void SayHello()
    {
        Console.WriteLine("Hello");
    }
}

任何人都可以解释为什么?

Can anyone explain why?

推荐答案

由于默认的构造函数A是私人的,请尝试保护A(){} 的构造。

Because the default constructor for A is private, try protected A() {} as the constructor.

B 自动调用 A 的默认构造函数,如果是无法访问或没有默认的构造函数(如果你有构造保护A(字符串s){} B 不能正确实例。

Class B automatically calls the default constructor of A, if that is inaccessible to B or there is no default constructor (if you have constructor protected A(string s) {}) B can not be instantiated correctly.

编译器会自动生成 B

public B() : base()
{
}

其中,基()是默认的构造函数 A 的实际调用。

Where base() is the actual call to the default constructor of A.