private(C# 参考)private (C# Reference)

private 关键字是一个成员访问修饰符。The private keyword is a member access modifier.

本页涵盖 private 访问。This page covers private access. private 关键字也是 private protected 访问修饰符的一部分。The private keyword is also part of the private protected access modifier.

私有访问是允许的最低访问级别。Private access is the least permissive access level. 私有成员只有在声明它们的类和结构体中才是可访问的,如以下示例所示:Private members are accessible only within the body of the class or the struct in which they are declared, as in this example:

class Employee
{
    private int i;
    double d;   // private access by default
}

同一体中的嵌套类型也可以访问那些私有成员。Nested types in the same body can also access those private members.

在声明私有成员的类或结构外引用它会导致编译时错误。It is a compile-time error to reference a private member outside the class or the struct in which it is declared.

有关 private 和其他访问修饰符的比较,请参阅可访问性级别访问修饰符For a comparison of private with the other access modifiers, see Accessibility Levels and Access Modifiers.

示例Example

在此示例中,Employee 类包含两个私有数据成员 namesalaryIn this example, the Employee class contains two private data members, name and salary. 作为私有成员,它们只能通过成员方法来访问。As private members, they cannot be accessed except by member methods. 添加名为 GetNameSalary 的公共方法,以便可以对私有成员进行受控的访问。Public methods named GetName and Salary are added to allow controlled access to the private members. 通过公共方法访问 name 成员,而通过公共只读属性访问 salary 成员。The name member is accessed by way of a public method, and the salary member is accessed by way of a public read-only property. (有关详细信息,请参阅属性。)(See Properties for more information.)

class Employee2
{
    private string name = "FirstName, LastName";
    private double salary = 100.0;

    public string GetName()
    {
        return name;
    }

    public double Salary
    {
        get { return salary; }
    }
}

class PrivateTest
{
    static void Main()
    {
        var e = new Employee2();

        // The data members are inaccessible (private), so
        // they 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# 语言规范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