Share via


如何宣告及使用讀寫屬性 (C# 程式設計指南)

屬性會提供公用資料成員的便利性,卻沒有不受保護、控制和驗證存取物件資料所附帶的風險。 屬性宣告「存取子」:從基礎資料成員指派和擷取值的特殊方法。 set 存取子可讓資料成員被指派,而 get 存取子可擷取資料成員值。

這個範例會示範有兩個屬性的 Person 類別:Name (字串) 和 Age (整數)。 這兩個屬性都提供 getset 存取子,所以會將它們視為讀寫屬性。

範例

class Person
{
    private string _name = "N/A";
    private int _age = 0;

    // Declare a Name property of type string:
    public string Name
    {
        get
        {
            return _name;
        }
        set
        {
            _name = value;
        }
    }

    // Declare an Age property of type int:
    public int Age
    {
        get
        {
            return _age;
        }

        set
        {
            _age = value;
        }
    }

    public override string ToString()
    {
        return "Name = " + Name + ", Age = " + Age;
    }
}

public class Wrapper
{
    private string _name = "N/A";
    public string Name
    {
        get
        {
            return _name;
        }
        private set
        {
            _name = value;
        }
    }

}

class TestPerson
{
    static void Main()
    {
        // Create a new Person object:
        Person person = new Person();

        // Print out the name and the age associated with the person:
        Console.WriteLine("Person details - {0}", person);

        // Set some values on the person object:
        person.Name = "Joe";
        person.Age = 99;
        Console.WriteLine("Person details - {0}", person);

        // Increment the Age property:
        person.Age += 1;
        Console.WriteLine("Person details - {0}", person);

        // Keep the console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    }
}
/* Output:
    Person details - Name = N/A, Age = 0
    Person details - Name = Joe, Age = 99
    Person details - Name = Joe, Age = 100
*/

穩固程式設計

在上例中,NameAge 屬性是公用的,且同時包含 getset 存取子。 公用存取子可讓任何物件讀取和寫入這些屬性。 但有時會想要排除其中一個存取子。 您可以省略 set 存取子,讓屬性變成唯讀:

public string Name
{
    get
    {
        return _name;
    }
    private set
    {
        _name = value;
    }
}

或者,您也可以向公眾公開某個存取子,但讓其他存取子為私用或受保護的。 如需詳細資訊,請參閱非對稱存取子的存取範圍

屬性一旦宣告之後,即可當成類別的欄位使用。 在取得和設定屬性值時,屬性能夠使用自然語法,如下列陳述式所示:

person.Name = "Joe";
person.Age = 99;

在屬性 set 方法中,提供特殊的 value 變數。 此變數包含使用者指定的值,例如:

_name = value;

請注意在 Person 物件上遞增 Age 屬性的全新語法:

person.Age += 1;

如果分別使用 setget 方法建立了屬性模型,對等的程式碼可能看起來像這樣:

person.SetAge(person.GetAge() + 1);

本例中覆寫 ToString 方法:

public override string ToString()
{
    return "Name = " + Name + ", Age = " + Age;
}

請注意,程式中未明確使用 ToString。 預設會由 WriteLine 呼叫來叫用。

另請參閱