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. 直接从 MainClass 访问 PointTest 的公共成员 xyThe 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