C# 3.0 - Object And Collection Initializers

C# 3.0 - Object And Collection Initializers

C# 3.0 新語法 Object Initializers,主要是用來簡化『物件初始化 』『設定屬性』,將兩者的動作化合而為一。以下範例,主要是實作 Product 類別練習 Object InitializersCollection Initializers 包含 Generic Collection List<T> Dictionary<TKey, TValue>

實作 Product 類別,並使用 Automatic Properties 來建立 ProductName ProductPrice 屬性:

   1:  public class Product
   2:  {
   3:      // Automatic properties
   4:      public string ProductName{ get; set; }
   5:      public int ProductPrice { get; set; }
   6:   
   7:      public override string ToString()
   8:      {
   9:          return string.Format("ProductName: {0}, ProductPrice: {1}", ProductName, ProductPrice);
  10:      }
  11:  }

 

 

一般類別變數宣告方式:

   1:  // 傳統宣告方式
   2:  Product p1 = new Product();
   3:  p1.ProductName = "A";
   4:  p1.ProductPrice = 100;
   5:  Console.WriteLine(p1.ToString());
   6:  /* Output:
   7:   * ProductName: A, ProductPrice: 100
   8:   */

 

 

Object Initializers:

   1:  // Object Initializers
   2:  Product p2 = new Product() { ProductName = "B", ProductPrice = 200 };
   3:  Console.WriteLine(p2.ToString());
   4:  /* Output: 
   5:   * ProductName: B, ProductPrice: 200
   6:   */

 

 

Object Initializers Without Constructor:

   1:  // Object Initializers Without Constructor
   2:  Product p3 = new Product { ProductName = "C", ProductPrice = 300 };
   3:  Console.WriteLine(p3.ToString());
   4:  /* Output:
   5:   * ProductName: C, ProductPrice: 300
   6:   */

 

 

Object and Collection Initializers Without Constructor:

   1:  // Object and Collection Initializers Without Constructor
   2:  List<Product> pList2 = new List<Product>
   3:  {
   4:      new Product { ProductName = "F", ProductPrice = 600 },
   5:      new Product { ProductName = "G", ProductPrice = 700 }
   6:  };
   7:  foreach (Product p in pList2)
   8:  {
   9:      Console.WriteLine(p.ToString());
  10:  }
  11:  /* Output:
  12:   * ProductName: F, ProductPrice: 600
  13:   * ProductName: G, ProductPrice: 700
  14:   */

Object and Dictionary Collection Initializers Without Constructor:

   1:  // Object and Dictionary Collection Initializers Without Constructor
   2:  Dictionary<string, Product> pDictionary = new Dictionary<string, Product>
   3:  {
   4:      {"HHH", new Product { ProductName = "H", ProductPrice = 800 } },
   5:      {"III", new Product { ProductName = "I", ProductPrice = 900 } }
   6:  };
   7:  foreach (KeyValuePair<string, Product> pPair in pDictionary)
   8:  {
   9:      Console.WriteLine(pPair.Value.ToString());
  10:  }
  11:  /* Output:
  12:   * ProductName: H, ProductPrice: 800
  13:   * ProductName: I, ProductPrice: 900
  14:   */