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