[英]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. 由于其保护级别,'CTest.AA()'无法访问。
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. 因为A的默认构造函数是private,所以尝试使用protected A() {}
作为构造函数。
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
无法访问或者没有默认构造函数(如果你有构造函数protected A(string s) {}
) B
无法正确实例化,则B
类自动调用A
的默认构造函数。
The compiler automatically generates the following default constructor in B
编译器在B
自动生成以下默认构造函数
public B() : base()
{
}
Where base()
is the actual call to the default constructor of A
. 其中base()
是对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. 类B
上的构造函数(由编译器添加)需要在A
上调用默认(no-args)构造函数,但是默认构造函数被标记为private
,这意味着它只能在A
调用,因此错误。
Change the constructor on A
to protected
or public
, or internal
if B
is in the same assembly. 如果B
在同一个程序集中,则将A
上的构造函数更改为protected
或public
,或者更改为internal
。
The constructor for A is private, it cannot be accessed from outside. A的构造函数是私有的,不能从外部访问。 If you want to create an instance of A from outside, make the constructor public or protected. 如果要从外部创建A的实例,请将构造函数设置为public或protected。
将private A()
更改为public A()
,你很高兴。
It's because A's constructor is private, but B's constructor is public. 这是因为A的构造函数是私有的,但B的构造函数是公共的。 When you construct B (which constructs A as well) there is no way to access A's private constructor. 当你构造B(也构造A)时,无法访问A的私有构造函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.