public (C# 參考)public (C# Reference)

public 關鍵字是類型和類型成員的存取修飾詞。The public keyword is an access modifier for types and type members. 公用存取是最寬鬆的存取層級。Public access is the most permissive access level. 不會限制存取公用成員,如此範例所示︰There are no restrictions on accessing public members, as in this example:

class SampleClass
{
    public int x; // No access restrictions.
}

如需詳細資訊,請參閱存取修飾詞存取範圍層級See Access Modifiers and Accessibility Levels for more information.

範例Example

在下列範例中,宣告兩個類別:PointTestMainClassIn the following example, two classes are declared, PointTest and MainClass. PointTest的公用成員 xy 直接存取自 MainClassThe public members x and y of PointTest are accessed directly from MainClass.

class PointTest
{
    public int x; 
    public int y;
}

class MainClass4
{
    static void Main() 
    {
        var p = new PointTest();
        // Direct access to public members.
        p.x = 10;
        p.y = 15;
        Console.WriteLine($"x = {p.x}, y = {p,y}"); 
    }
}
// Output: x = 10, y = 15

如果您將 public 存取層級變更為 privateprotected,則會收到錯誤訊息:If you change the public access level to private or protected, you will get the error message:

'PointTest.y' 的保護層級導致無法對其進行存取。'PointTest.y' is inaccessible due to its protection level.

C# 語言規格C# language specification

如需詳細資訊,請參閱 C# 語言規格已宣告存取範圍For more information, see Declared accessibility in the C# Language Specification. 語言規格是 C# 語法及用法的限定來源。The language specification is the definitive source for C# syntax and usage.

另請參閱See also