简体   繁体   中英

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

I am getting this error:

'CTest.AA()' 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.

private A()更改为public A() ,你很高兴。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM