自动实现的属性(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 访问器为专用(对使用者的不可变)或通过声明仅一个 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