C# 筆記:自動實作屬性與物件初始器

C# 3.0 增加了自動實作屬性(auto-implementation property)與物件初始器(object initializer)的語法。這兩種語法都提供了某種程度的方便性,Scott Guthrie 很早就寫了一篇文章介紹它們,這裡就不寫太多重複的東西了。貼個簡單的範例上來:

   1:      public class Employee
   2:      {
   3:          public string Name    // 這是一個 auto-implementation property.
   4:          {
   5:              get;
   6:              set;
   7:          }
   8:  
   9:          public int Age        // 這也是個 auto-implementation property.
  10:          {
  11:              get;
  12:              set;    // 若改為 private set(即 read only),就算用
object initializer 語法也無法設定此屬性.
  13:          }
  14:      }
  15:  
  16:      class Program
  17:      {
  18:          static void Main(string[] args)
  19:          {
  20:              // 示範 object initializer 寫法
  21:              Employee emp = new Employee
  22:              {
  23:                  Name = "Michael",
  24:                  Age = 20
  25:              };
  26:          }
  27:      }

編譯器會替 Employee 的 Name 和 Age 屬性產生兩個 private 成員,而這種由 auto-implementation property 所產生的類別成員有個專門的稱呼,叫做 backing field。此 syntax sugar 的方便之處即在於當我們碰到一些單純需要定義類別屬性來儲存資料的場合時,用這種語法就可以省掉自行宣告私有成員的步驟(就是少打一些字啦!)。

最後附上 ILDASM 反組譯的結果,看看編譯器產生的 backing fields 到底長甚麼樣子:

.field private int32 <Age>k__BackingField
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor()
}

.field private string <Name>k__BackingField
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor()
}
相關文章

沒有留言:

技術提供:Blogger.
回頂端⬆️