private 关键字是一个成员访问修饰符。私有访问是允许的最低访问级别。私有成员只有在声明它们的类和结构体中才是可访问的,如下例所示:
| 复制代码 |
---|
class Employee
{
private int i;
double d; // private access by default
} |
同一体中的嵌套类型也可以访问那些私有成员。
在定义私有成员的类或结构外引用它会导致编译时错误。
有关 private 与其他访问修饰符的比较,请参见可访问性级别和访问修饰符(C# 编程指南)。
示例
在此示例中,Employee
类包含两个私有数据成员 name
和 salary
。作为私有成员,它们只能通过成员方法来访问,因此,添加了名为 GetName
和 Salary
的公共方法,以允许对私有成员进行受控制的访问。name
成员通过公共方法来访问,salary
成员通过一个公共只读属性来访问。(有关更多信息,请参见属性(C# 编程指南)。)
| 复制代码 |
---|
// private_keyword.cs
using System;
class Employee
{
private string name = "FirstName, LastName";
private double salary = 100.0;
public string GetName()
{
return name;
}
public double Salary
{
get { return salary; }
}
}
class MainClass
{
static void Main()
{
Employee e = new Employee();
// The data members are inaccessible (private), so
// then can't be accessed like this:
// string n = e.name;
// double s = e.salary;
// 'name' is indirectly accessed via method:
string n = e.GetName();
// 'salary' is indirectly accessed via property
double s = e.Salary;
}
} |
C# 语言规范
请参见