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

此頁面涵蓋 static 修飾詞關鍵字。This page covers the static modifier keyword. static關鍵字也是指示詞的一部分 using staticThe static keyword is also part of the using static directive.

使用 static 修飾詞來宣告靜態成員,而靜態成員屬於類型本身,而不是特定物件。Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object. static修飾詞可以用來宣告 static 類別。The static modifier can be used to declare static classes. 在類別、介面和結構中,您可以將修飾詞加入 static 至欄位、方法、屬性、運算子、事件和函式。In classes, interfaces, and structs, you may add the static modifier to fields, methods, properties, operators, events, and constructors. static修飾元無法與索引子或完成項一起使用。The static modifier can't be used with indexers or finalizers. 如需詳細資訊,請參閱 靜態類別和靜態類別成員For more information, see Static Classes and Static Class Members.

從 c # 8.0 開始,您可以將 static 修飾詞加入至 區域函數Beginning with C# 8.0, you can add the static modifier to a local function. 靜態區域函式無法捕捉本機變數或實例狀態。A static local function can't capture local variables or instance state.

從 c # 9.0 開始,您可以將 static 修飾詞加入至 lambda 運算式匿名方法Beginning with C# 9.0, you can add the static modifier to a lambda expression or anonymous method. 靜態 lambda 或匿名方法無法捕捉本機變數或實例狀態。A static lambda or anonymous method can't capture local variables or instance state.

範例-靜態類別Example - static class

下列類別宣告為 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() { /*...*/  }
}

常數或型別宣告是隱含的 static 成員。A constant or type declaration is implicitly a static member. static無法透過實例參考成員。A static member can't be referenced through an instance. 相反地,它是透過型別名稱來參考。Instead, it's referenced through the type name. 例如,請參考下列類別:For example, consider the following class:

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

若要參考該 static 成員 x ,請使用完整名稱, MyBaseC.MyStruct.x 除非該成員可以從相同範圍存取:To 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);

雖然類別的實例包含類別的所有實例欄位的個別複本,但每個欄位只有一個複本 staticWhile an instance of a class contains a separate copy of all instance fields of the class, there's only one copy of each static field.

您無法使用 this 參考 static 方法或屬性存取子。It isn't possible to use this to reference static methods or property accessors.

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

類別、介面和 static 類別可能具有函式 staticClasses, interfaces, and static classes may have static constructors. static 程式啟動和具現化類別之間的某個時間點,會呼叫一個函數。A static constructor is 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++).

若要示範 static 成員,請考慮代表公司員工的類別。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 don't belong to any one employee instance. 相反地,它們屬於整個員工的類別。Instead, they belong to the class of employees as a whole. 它們應該宣告為 static 類別的成員。They should be declared as static members of the class.

範例-靜態欄位和方法Example - static field and method

這個範例會讀取新員工的名稱和識別碼,並將員工計數器遞加一,然後顯示新員工和新員工人數的資訊。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. 此程式會從鍵盤讀取目前的員工數目。This program reads the current number of employees from the keyboard.

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 - static initialization

此範例顯示您可以使用尚未宣告的 static 其他欄位來初始化欄位 staticThis example shows that you can initialize a static field by using another static field that is not yet declared. 在您明確指派值給欄位之前,將不會定義結果 staticThe 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