欄位 (C# 程式設計手冊)Fields (C# Programming Guide)

「欄位」是任意類型的變數,可在類別結構中直接宣告。A field is a variable of any type that is declared directly in a class or struct. 欄位是其包含類型的「成員」。Fields are members of their containing type.

類別或結構可能會有執行個體欄位或靜態欄位,或者兩者都有。A class or struct may have instance fields or static fields or both. 執行個體欄位是專屬於某種類型的執行個體。Instance fields are specific to an instance of a type. 如果您有搭配執行個體欄位 F 的類別 T,您可以建立兩個類型 T 的物件,然後修改每個物件中的 F 值,而不會影響另一個物件中的值。If you have a class T, with an instance field F, you can create two objects of type T, and modify the value of F in each object without affecting the value in the other object. 相較之下,靜態欄位屬類別本身所擁有,並在該類別的所有執行個體之間共用。By contrast, a static field belongs to the class itself, and is shared among all instances of that class. 對執行個體 A 所做的變更,執行個體 B 和 C 只要存取該欄位就會立即看到。Changes made from instance A will be visibly immediately to instances B and C if they access the field.

一般而言,您應該只針對具有 private 或 protected 存取範圍的變數使用欄位。Generally, you should use fields only for variables that have private or protected accessibility. 您的類別公開給用戶端程式碼的資料應透過方法屬性索引子來提供。Data that your class exposes to client code should be provided through methods, properties and indexers. 藉由使用這些建構來間接存取內部欄位,即可防範無效的輸入值。By using these constructs for indirect access to internal fields, you can guard against invalid input values. 儲存由公用屬性公開之資料的私用欄位稱為「備份存放區」或「支援欄位」。A private field that stores the data exposed by a public property is called a backing store or backing field.

這些欄位通常會儲存必須可供多個類別方法存取的資料,以及其儲存時間必須比任何一個方法的存留期都還要長的資料。Fields typically store the data that must be accessible to more than one class method and must be stored for longer than the lifetime of any single method. 例如,表示行事曆日期的類別可能會有三個整數欄位,分別代表月、日和年。For example, a class that represents a calendar date might have three integer fields: one for the month, one for the day, and one for the year. 未在單一方法以外範圍使用的變數,應在方法主體本身內宣告為「區域變數」。Variables that are not used outside the scope of a single method should be declared as local variables within the method body itself.

請依序指定欄位的存取層級、欄位的類型和欄位的名稱,以在類別區塊中宣告欄位。Fields are declared in the class block by specifying the access level of the field, followed by the type of the field, followed by the name of the field. 例如:For example:

   public class CalendarEntry
   {
       // private field
       private DateTime date;

       // public field (Generally not recommended.)
       public string day;

       // Public property exposes date field safely.
       public DateTime Date 
       {
           get 
           {
               return date;
           }
           set 
           {
               // Set some reasonable boundaries for likely birth dates.
               if (value.Year > 1900 && value.Year <= DateTime.Today.Year)
               {
                   date = value;
               }
               else
                   throw new ArgumentOutOfRangeException();
           }

       }

       // Public method also exposes date field safely.
       // Example call: birthday.SetDate("1975, 6, 30");
       public void SetDate(string dateString)
       {
           DateTime dt = Convert.ToDateTime(dateString);

           // Set some reasonable boundaries for likely birth dates.
           if (dt.Year > 1900 && dt.Year <= DateTime.Today.Year)
           {
               date = dt;
           }
           else
               throw new ArgumentOutOfRangeException();
       }

       public TimeSpan GetTimeSpan(string dateString)
       {
           DateTime dt = Convert.ToDateTime(dateString);

           if (dt != null && dt.Ticks < date.Ticks)
           {
               return date - dt;
           }
           else
               throw new ArgumentOutOfRangeException();  

       }
   }

若要存取物件中的欄位,請在物件名稱後面加上句號,再加上欄位的名稱,就像是 objectname.fieldnameTo access a field in an object, add a period after the object name, followed by the name of the field, as in objectname.fieldname. 例如:For example:

CalendarEntry birthday = new CalendarEntry();
birthday.day = "Saturday";

您可以在宣告欄位時,使用指派運算子來指定欄位的初始值。A field can be given an initial value by using the assignment operator when the field is declared. 例如,若要將 day 欄位自動指派為 "Monday",您可以如下列範例所示宣告 dayTo automatically assign the day field to "Monday", for example, you would declare day as in the following example:

public class CalendarDateWithInitialization
{
    public string day = "Monday";
    //...
}

欄位會在呼叫物件執行個體的建構函式之前立即初始化。Fields are initialized immediately before the constructor for the object instance is called. 如果建構函式指派了欄位的值,該值會覆寫欄位宣告期間所指定的任何值。If the constructor assigns the value of a field, it will overwrite any value given during field declaration. 如需詳細資訊,請參閱使用建構函式For more information, see Using Constructors.

注意

欄位初始設定式無法參考其他執行個體欄位。A field initializer cannot refer to other instance fields.

欄位可以標記為 publicprivateprotectedinternalprotected internalprivate protectedFields can be marked as public, private, protected, internal, protected internal or private protected. 這些存取修飾詞定義類別使用者如何存取欄位。These access modifiers define how users of the class can access the fields. 如需詳細資訊,請參閱存取修飾詞For more information, see Access Modifiers.

欄位可以選擇性地宣告為 staticA field can optionally be declared static. 這可隨時向呼叫者提供欄位,即使沒有任何類別執行個體存在。This makes the field available to callers at any time, even if no instance of the class exists. 如需詳細資訊,請參閱靜態類別和靜態類別成員For more information, see Static Classes and Static Class Members.

欄位可以宣告為 readonlyA field can be declared readonly. 您只能在初始化期間或在建構函式中指派值給唯讀欄位。A read-only field can only be assigned a value during initialization or in a constructor. static readonly 欄位非常類似於常數,不同之處在於 C# 編譯器無法在編譯時期存取靜態唯讀欄位的值,只有在執行階段才能這麼做。A static readonly field is very similar to a constant, except that the C# compiler does not have access to the value of a static read-only field at compile time, only at run time. 如需詳細資訊,請參閱常數For more information, see Constants.

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