开发者

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

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?


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.


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.


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜