最近閱讀 MVA C# Fundamentals for Absolute Beginners - 22 Working with Collections 章節時才發現,原來從 3.0 開始就有 "物件初始化" 功能可以便捷地 new class 並設定 property 值
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<demo> demoList1 = new List<demo>();
// [C#] 根據 CheckBox 來顯示 DataGridView 欄位 2 作法
// new class 出來後,針對 property 設定值
demo test1 = new demo();
test1.property1 = "1";
test1.property2 = "1";
demoList1.Add(test1);
// [C#] 動態產生內含 6 個 CheckBox 的 Panel 作法
// 建立一個符合 property 數量的建構子,new class 時一併把 property 值傳入 class 去進行設定
demo test2 = new demo("2", "2");
demoList1.Add(test2);
// MVA C# Fundamentals for Absolute Beginners - 22 Working with Collections
// 以下從影片中學習到的
// 物件初始化設定:不用建立符合 property 數量的建構子
demo test3 = new demo() { property1 = "3", property2 = "3" };
demoList1.Add(test3);
// 此 test4 範例,但 code 的目的只是為了把資料篩進 demoList 中,該 class 名稱並不重要,如同下段 code
demoList1.Add(new demo() { property1 = "4", property2 = "4" });
// 集合初始設定
// 集合初始設定式是一系列以逗號分隔的物件初始設定式
List<demo> demolist2 = new List<demo>()
{
new demo(){property1 = "5", property2 ="5"},
new demo(){property1 = "6", property2 ="6"}
};
// 把兩個 List 內資料都顯示出來
foreach (demo item in demoList1)
{
Console.WriteLine("{0}", item.property1);
}
foreach (demo item in demolist2)
{
Console.WriteLine("{0}", item.property1);
}
}
class demo
{
public string property1 { get; set; }
public string property2 { get; set; }
// [C#] 動態產生內含 6 個 CheckBox 的 Panel 作法
public demo(string _property1, string _property2)
{
this.property1 = _property1;
this.property2 = _property2;
}
public demo() { }
}
}
}
![[C#] 物件初始化](https://farm3.staticflickr.com/2929/14815268472_5592950541_o.jpg)
沒有留言:
張貼留言