共用方式為


使用輔助功能層級的限制 (C# 參考)

當您在宣告中指定類型時,請檢查型別的存取層級是否相依於成員的存取層級或另一種型別的存取層級。 例如,直接基類至少必須和衍生類別一樣可存取。 下列宣告會造成編譯程式錯誤,因為基類 BaseClass 的存取量小於 MyClass

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

下表摘要說明宣告輔助功能層級的限制。

上下文 備註
類別 類別類型的直接基類至少必須和類別類型本身一樣可存取。
介面 介面類型的明確基底介面必須至少和介面類型本身一樣可存取。
代表 委派類型的傳回型別和參數型別至少必須和委派類型本身一樣可存取。
常數 常數的類型至少必須和常數本身一樣可存取。
欄位 欄位的類型至少必須和欄位本身一樣可存取。
方法 方法的傳回型別和參數型別至少必須和方法本身一樣可存取。
性能 屬性的類型至少必須和屬性本身一樣可存取。
活動 事件的類型至少必須和事件本身一樣可存取。
索引器 索引器的類型和參數類型至少必須和索引器本身一樣可存取。
運算子 運算子的傳回型別和參數類型至少必須和運算符本身一樣可存取。
建構函式 建構函式的參數類型至少必須和建構函式本身一樣可存取。

範例

下列範例包含不同類型的錯誤宣告。 每個宣告後面的批注表示預期的編譯程序錯誤。

// 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# 語法和使用方式的最終來源。

另請參閱