屬性提供公用數據成員的便利性,而沒有未受保護、不受控制且未驗證存取對象數據的風險。 屬性會宣告 存取子:從基礎數據成員指派和擷取值的特殊方法。 設定 存取子允許指派數據成員,而 取得 存取子用於擷取數據成員值。
此範例顯示具有兩個屬性的 Person 類別:Name (string) 和 Age (int)。 這兩個屬性都提供 get 和 set 存取子,因此會被視為讀取/寫入屬性。
範例
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 - {person}");
// Set some values on the person object:
person.Name = "Joe";
person.Age = 99;
Console.WriteLine($"Person details - {person}");
// Increment the Age property:
person.Age += 1;
Console.WriteLine($"Person details - {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
*/
健全的程式設計
在上一個範例中,Name 和 Age 屬性是 公共的,並同時包含 get 和 set 存取子。 公用存取子允許任何物件讀取和寫入這些屬性。 不過,有時最好排除其中一個存取子。 您可以省略 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;
如果使用個別 set 和 get 方法來建立屬性模型,則對等程式代碼看起來可能如下所示:
person.SetAge(person.GetAge() + 1);
在此範例中,ToString 方法被重寫:
public override string ToString()
{
return "Name = " + Name + ", Age = " + Age;
}
請注意,ToString 不會在程序中明確使用。 預設情況下,由 WriteLine 呼叫。