可访问性级别的使用限制
声明类型时,请确保查看该类型是否必须至少具有与另一个成员或类型相同的可访问性。例如,直接基类必须至少与派生类具有同样的可访问性。以下声明将导致编译器错误,因为基类BaseClass 的可访问性小于 MyClass:
class BaseClass {...} public class MyClass: BaseClass {...} // Error |
本在线速查手册由www.w〔3〔x〔u〔e.com提供,请勿盗用!
下表汇总了对使用声明的可访问性级别的限制。
上下文 |
备注 |
---|---|
|
类类型的直接基类必须至少与类类型本身具有同样的可访问性。 |
|
接口类型的显式基接口必须至少与接口类型本身具有同样的可访问性。 |
|
委托类型的返回类型和参数类型必须至少与委托类型本身具有同样的可访问性。 |
|
常数的类型必须至少与常数本身具有同样的可访问性。 |
|
字段的类型必须至少与字段本身具有同样的可访问性。 |
|
方法的返回类型和参数类型必须至少与方法本身具有同样的可访问性。 |
|
属性的类型必须至少与属性本身具有同样的可访问性。 |
|
事件的类型必须至少与事件本身具有同样的可访问性。 |
|
索引器的类型和参数类型必须至少与索引器本身具有同样的可访问性。 |
|
运算符的返回类型和参数类型必须至少与运算符本身具有同样的可访问性。 |
|
构造函数的参数类型必须至少与构造函数本身具有同样的可访问性。 |
本在线速查手册由www.w〔3〔x〔u〔e.com提供,请勿盗用!
示例
下面的示例包含不同类型的错误声明。每个声明后的注释指示了预期的编译器错误。
// Restrictions on Using Accessibility Levels // 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"); } } |
本在线速查手册由www.w〔3〔x〔u〔e.com提供,请勿盗用!