static (C# 參考)static (C# Reference)

使用 static 修飾詞來宣告靜態成員,而靜態成員屬於類型本身,而不是特定物件。Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object. static 修飾詞可以與類別、欄位、方法、屬性、運算子、事件和建構函式搭配使用,但不能與索引子、完成項或類別以外的類型搭配使用。The static modifier can be used with classes, fields, methods, properties, operators, events, and constructors, but it cannot be used with indexers, finalizers, or types other than classes. 如需詳細資訊,請參閱靜態類別和靜態類別成員For more information, see Static Classes and Static Class Members.

範例Example

下列類別宣告為 static,並且只包含 static 方法:The following class is declared as static and contains only static methods:

static class CompanyEmployee
{
    public static void DoSomething() { /*...*/ }
    public static void DoSomethingElse() { /*...*/  }
}

常數或型別宣告隱含為靜態成員。A constant or type declaration is implicitly a static member.

靜態成員無法透過執行個體進行參考。A static member cannot be referenced through an instance. 而是透過類型名稱進行參考。Instead, it is referenced through the type name. 例如,請參考下列類別:For example, consider the following class:

public class MyBaseC
{
    public struct MyStruct
    {
        public static int x = 100;
    }
}

若要參照靜態成員 x,除非可以從相同的範圍存取該成員,否則請使用完整名稱 MyBaseC.MyStruct.xTo refer to the static member x, use the fully qualified name, MyBaseC.MyStruct.x, unless the member is accessible from the same scope:

Console.WriteLine(MyBaseC.MyStruct.x);

雖然類別的執行個體包含類別的所有執行個體欄位的個別複本,但是每個靜態欄位都只會有一個複本。While an instance of a class contains a separate copy of all instance fields of the class, there is only one copy of each static field.

無法使用 this 來參考靜態方法或屬性存取子。It is not possible to use this to reference static methods or property accessors.

如果將 static 關鍵字套用至類別,則類別的所有成員都必須是靜態。If the static keyword is applied to a class, all the members of the class must be static.

類別和靜態類別可能會有靜態建構函式。Classes and static classes may have static constructors. 在啟動程式時與具現化類別時之間的某個點,會呼叫靜態建構函式。Static constructors are called at some point between when the program starts and the class is instantiated.

注意

static 關鍵字的使用方式比在 C++ 中受到更多限制。The static keyword has more limited uses than in C++. 若要與 C++ 關鍵字進行比較,請參閱儲存類別 (C++)To compare with the C++ keyword, see Storage classes (C++).

若要示範靜態成員,請考慮使用代表公司員工的類別。To demonstrate static members, consider a class that represents a company employee. 假設此類別包含可計算員工人數的方法以及可儲存員工人數的欄位。Assume that the class contains a method to count employees and a field to store the number of employees. 方法和欄位都不屬於任何執行個體員工。Both the method and the field do not belong to any instance employee. 相反地,它們屬於公司類別。Instead they belong to the company class. 因此,它們應該宣告為類別的靜態成員。Therefore, they should be declared as static members of the class.

範例Example

這個範例會讀取新員工的名稱和識別碼,並將員工計數器遞加一,然後顯示新員工和新員工人數的資訊。This example reads the name and ID of a new employee, increments the employee counter by one, and displays the information for the new employee and the new number of employees. 為求簡單,此程式會從鍵盤讀取目前的員工人數。For simplicity, this program reads the current number of employees from the keyboard. 在實際的應用程式中,應該從檔案讀取這項資訊。In a real application, this information should be read from a file.

public class Employee4
{
    public string id;
    public string name;

    public Employee4()
    {
    }

    public Employee4(string name, string id)
    {
        this.name = name;
        this.id = id;
    }

    public static int employeeCounter;

    public static int AddEmployee()
    {
        return ++employeeCounter;
    }
}

class MainClass : Employee4
{
    static void Main()
    {
        Console.Write("Enter the employee's name: ");
        string name = Console.ReadLine();
        Console.Write("Enter the employee's ID: ");
        string id = Console.ReadLine();

        // Create and configure the employee object.
        Employee4 e = new Employee4(name, id);
        Console.Write("Enter the current number of employees: ");
        string n = Console.ReadLine();
        Employee4.employeeCounter = Int32.Parse(n);
        Employee4.AddEmployee();

        // Display the new information.
        Console.WriteLine($"Name: {e.name}");
        Console.WriteLine($"ID:   {e.id}");
        Console.WriteLine($"New Number of Employees: {Employee4.employeeCounter}");
    }
}
/*
Input:
Matthias Berndt
AF643G
15
 * 
Sample Output:
Enter the employee's name: Matthias Berndt
Enter the employee's ID: AF643G
Enter the current number of employees: 15
Name: Matthias Berndt
ID:   AF643G
New Number of Employees: 16
*/

範例Example

這個範例示範,雖然您可以使用另一個尚未宣告的靜態欄位來初始化靜態欄位,但是除非將值明確指派給靜態欄位,否則不會定義結果。This example shows that although you can initialize a static field by using another static field not yet declared, the results will be undefined until you explicitly assign a value to the static field.

class Test
{
    static int x = y;
    static int y = 5;

    static void Main()
    {
        Console.WriteLine(Test.x);
        Console.WriteLine(Test.y);

        Test.x = 99;
        Console.WriteLine(Test.x);
    }
}
/*
Output:
    0
    5
    99
*/

C# 語言規格C# language specification

如需詳細資訊,請參閱<C# 語言規格>。For more information, see the C# Language Specification. 語言規格是 C# 語法及用法的限定來源。The language specification is the definitive source for C# syntax and usage.

另請參閱See also