自動實作的屬性 (C# 程式設計手冊)Auto-Implemented Properties (C# Programming Guide)

在 C# 3.0 及更新版本中,當屬性存取子中不需要額外的邏輯時,自動實作的屬性可讓屬性宣告變得更精簡。In C# 3.0 and later, auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors. 它們還可讓用戶端程式碼建立物件。They also enable client code to create objects. 當您宣告屬性時,如下列範例所示,編譯器會建立私用、匿名的支援欄位,但只能透過屬性的 getset 存取子才能存取。When you declare a property as shown in the following example, the compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.

範例Example

下列範例示範一個簡單的類別,其中包含一些自動實作的屬性:The following example shows a simple class that has some auto-implemented properties:

// This class is mutable. Its data can be modified from
// outside the class.
class Customer
{
    // Auto-implemented properties for trivial get and set
    public double TotalPurchases { get; set; }
    public string Name { get; set; }
    public int CustomerID { get; set; }

    // Constructor
    public Customer(double purchases, string name, int ID)
    {
        TotalPurchases = purchases;
        Name = name;
        CustomerID = ID;
    }

    // Methods
    public string GetContactInfo() { return "ContactInfo"; }
    public string GetTransactionHistory() { return "History"; }

    // .. Additional methods, events, etc.
}

class Program
{
    static void Main()
    {
        // Intialize a new object.
        Customer cust1 = new Customer(4987.63, "Northwind", 90108);

        // Modify a property.
        cust1.TotalPurchases += 499.99;
    }
}

在 C# 6 及更新版本中,您可以初始化自動實作的屬性,就像欄位一樣:In C# 6 and later, you can initialize auto-implemented properties similarly to fields:

public string FirstName { get; set; } = "Jane";  

先前範例中顯示的類別可變動。The class that is shown in the previous example is mutable. 用戶端程式碼可以在物件建立之後變更其中的值。Client code can change the values in objects after they are created. 在包含重要行為 (方法) 和資料的複雜類別中,通常需要有公用屬性。In complex classes that contain significant behavior (methods) as well as data, it is often necessary to have public properties. 不過,對於只封裝一組值 (資料) 且只有很少甚至沒有行為的小型類別或結構,您應該將 set 存取子宣告為 private (對取用者而言不可變),或只宣告 get 存取子 (除了建構函式,在其他任何地方都不可變動),將物件變成不可變動。However, for small classes or structs that just encapsulate a set of values (data) and have little or no behaviors, you should either make the objects immutable by declaring the set accessor as private (immutable to consumers) or by declaring only a get accessor (immutable everywhere except the constructor). 如需詳細資訊,請參閱如何:使用自動實作的屬性來實作輕量型類別For more information, see How to: Implement a Lightweight Class with Auto-Implemented Properties.

另請參閱See also