var p = new Point() { X = 100, Y = 200 }; // 默認構造
var p = new Point(10, 20) { X = 100, Y = 200 }; // 自定義構造:參數被忽略,屬性賦值生效
enum PointColor { White, Black, Green, Blue }
class Point
{
private int xPos, yPos;
private PointColor c;
public Point() { }
public Point(PointColor color) { xPos = 0; yPos = 0; c = color; }
public Point(int x, int y) { xPos = x; yPos = y; c = PointColor.Green; }
public int X { get => xPos; set => xPos = value; }
public int Y { get => yPos; set => yPos = value; }
public PointColor Color { get => c; set => c = value; }
public override string ToString() => $"[{X}, {Y}, Color={Color}]";
}
// 指定顏色構造,再覆蓋坐標
var p = new Point(PointColor.Blue) { X = 100, Y = 200 };
// 結果:X=100, Y=200, Color=Blue
ICollection<T>.Add(T)ICollection<T> 的類型(如 ArrayList)不可用
// 合法
List list = new List { 0,1,2,3,4,5,6,7,8,9 };
// 非法
ArrayList arr = new ArrayList { 0,1,2,3 }; // ❌ 編譯錯誤
對象初始化器支持顯式調用任意構造函數,構造參數與屬性賦值互不干擾(賦值後生效)。擴展類型增加構造函數參數(如色彩)配合初始化器,實現「預設 + 覆蓋」靈活模式。集合初始化器嚴格要求 ICollection<T>,編譯器展開為循環 Add 調用。