Why am I getting an “inaccessible due to protection level” error?

本小妞迷上赌 提交于 2020-01-05 00:40:50

问题


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?


回答1:


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.




回答2:


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.




回答3:


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:


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




回答5:


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.



来源:https://stackoverflow.com/questions/5326057/why-am-i-getting-an-inaccessible-due-to-protection-level-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!