声明类型时,最重要的是查看该类型是否必须至少与其他成员或类型具有同样的可访问性。例如,直接基类必须至少与派生类具有同样的可访问性。以下声明将导致编译器错误,因为基类 BaseClass
的可访问性小于 MyClass
:
| 复制代码 |
---|
class BaseClass {...}
public class MyClass: BaseClass {...} // Error |
下表汇总了对使用声明的可访问性级别的限制。
上下文
|
备注
|
类
|
类类型的直接基类必须至少与类类型本身具有同样的可访问性。
|
接口
|
接口类型的显式基接口必须至少与接口类型本身具有同样的可访问性。
|
委托
|
委托类型的返回类型和参数类型必须至少与委托类型本身具有同样的可访问性。
|
常数
|
常数的类型必须至少与常数本身具有同样的可访问性。
|
字段
|
字段的类型必须至少与字段本身具有同样的可访问性。
|
方法
|
方法的返回类型和参数类型必须至少与方法本身具有同样的可访问性。
|
属性
|
属性的类型必须至少与属性本身具有同样的可访问性。
|
事件
|
事件的类型必须至少与事件本身具有同样的可访问性。
|
索引器
|
索引器的类型和参数类型必须至少与索引器本身具有同样的可访问性。
|
运算符
|
运算符的返回类型和参数类型必须至少与运算符本身具有同样的可访问性。
|
构造函数
|
构造函数的参数类型必须至少与构造函数本身具有同样的可访问性。
|
示例
下面的示例包含不同类型的错误声明。每个声明后的注释指示了预期的编译器错误。
| 复制代码 |
---|
// Restrictions_on_Using_Accessibility_Levels.cs
// CS0052 expected as well as CS0053, CS0056, and CS0057
// To make the program work, change access level of both class B
// and MyPrivateMethod() to public.
using System;
// A delegate:
delegate int MyDelegate();
class B
{
// A private method:
static int MyPrivateMethod()
{
return 0;
}
}
public class A
{
// Error: The type B is less accessible than the field A.myField.
public B myField = new B();
// Error: The type B is less accessible
// than the constant A.myConst.
public readonly B myConst = new B();
public B MyMethod()
{
// Error: The type B is less accessible
// than the method A.MyMethod.
return new B();
}
// Error: The type B is less accessible than the property A.MyProp
public B MyProp
{
set
{
}
}
MyDelegate d = new MyDelegate(B.MyPrivateMethod);
// Even when B is declared public, you still get the error:
// "The parameter B.MyPrivateMethod is not accessible due to
// protection level."
public static B operator +(A m1, B m2)
{
// Error: The type B is less accessible
// than the operator A.operator +(A,B)
return new B();
}
static void Main()
{
Console.Write("Compiled successfully");
}
} |
C# 语言规范
请参见