public(C# 参考)
public
关键字是类型和类型成员的访问修饰符。 公共访问是允许的最高访问级别。 对访问公共成员没有限制,如以下示例所示:
class SampleClass
{
public int x; // No access restrictions.
}
示例
在下面的示例中,声明了两个类:PointTest
和 Program
。 直接从 Program
访问 PointTest
的公共成员 x
和 y
。
class PointTest
{
public int x;
public int y;
}
class Program
{
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
访问级别更改为 private 或 protected,则会收到错误消息:
“PointTest.y”不可访问,因为它受保护级别限制。
C# 语言规范
有关详细信息,请参阅 C# 语言规范中的声明的可访问性。 该语言规范是 C# 语法和用法的权威资料。
另请参阅
Collaborate with us on GitHub
The source for this content can be found on GitHub, where you can also create and review issues and pull requests. For more information, see our contributor guide.
.NET feedback
The .NET documentation is open source. Provide feedback here.
反馈
提交和查看相关反馈