自 Visual Studio Orcas March CTP 發布以來,許多部落格探討其新特性。Scott Guthrie 近期在部落格發文介紹 C# 3.0 重點特性,首推自動屬性。
傳統寫法需手工聲明私有欄位與 get/set 存取器:
public class Person {
private string _firstName;
private string _lastName;
private int _age;
public string FirstName {
get { return _firstName; }
set { _firstName = value; }
}
public string LastName {
get { return _lastName; }
set { _lastName = value; }
}
public int Age {
get { return _age; }
set { _age = value; }
}
}
使用自動屬性可簡化為:
public class Person {
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}
甚至可進一步緊湊排版。編譯器遇到空白的 get; set; 時,會自動生成私有備用欄位並實現公開的 getter/setter。從類型契約角度看,與手寫版本完全一致。優勢在於未來可在 setter 中加入驗證邏輯,無需變更外部組件介面。