Why am I getting an “inaccessible due to protectio

2019-07-20 16:57发布

I am getting this error:

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

when compiling this code:

public class A
{
    private A()
    {
    }
}

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

Can anyone explain why?

5条回答
SAY GOODBYE
2楼-- · 2019-07-20 17:28

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

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.

The compiler automatically generates the following default constructor in B

public B() : base()
{
}

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

查看更多
等我变得足够好
3楼-- · 2019-07-20 17:30

The constructor for A is private, it cannot be accessed from outside. If you want to create an instance of A from outside, make the constructor public or protected.

查看更多
仙女界的扛把子
4楼-- · 2019-07-20 17:34

The constructor on class B (which is added by the compiler) needs to call the default (no-args) constructor on A, however the default constructor is marked as private, which means it can only be called inside A, hence the error.

Change the constructor on A to protected or public, or internal if B is in the same assembly.

查看更多
戒情不戒烟
5楼-- · 2019-07-20 17:39

It's because A's constructor is private, but B's constructor is public. When you construct B (which constructs A as well) there is no way to access A's private constructor.

查看更多
干净又极端
6楼-- · 2019-07-20 17:47

Change private A() to public A() and you are good to go.

查看更多
登录 后发表回答