使用辅助功能级别的限制 (C# 参考)

在声明中指定类型时,请检查该类型的辅助功能级别是否依赖于成员的辅助功能级别或其他类型的辅助功能级别。 例如,直接基类必须至少与派生类一样易于访问。 以下声明会导致编译器错误,因为基类 BaseClass 的可访问性小于 MyClass

class BaseClass {...}
public class MyClass: BaseClass {...} // Error

下表总结了对声明的辅助功能级别的限制。

上下文 注解
类类型的直接基类必须至少与类类型本身一样可访问。
接口 接口类型的显式基接口必须至少可以像接口类型本身一样易于访问。
代表 委托类型的返回类型和参数类型必须至少与委托类型本身一样可访问。
常量 常量的类型必须至少与常量本身一样可访问。
字段 字段的类型必须至少与字段本身一样可访问。
方法 方法的返回类型和参数类型必须至少与方法本身一样易于访问。
性能 属性的类型必须至少与属性本身一样可访问。
事件 事件的类型必须至少与事件本身一样可访问。
Indexers 索引器的类型和参数类型必须至少与索引器本身一样可访问。
操作员 运算符的返回类型和参数类型必须至少与运算符本身一样可访问。
构造函数 构造函数的参数类型必须至少与构造函数本身一样易于访问。

示例:

以下示例包含不同类型的错误声明。 每个声明后面的注释指示预期的编译器错误。

// 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");
    }
}

C# 语言规范

有关详细信息,请参阅 C# 语言规范。 语言规范是 C# 语法和用法的明确来源。

另请参阅