// 隱式默認構造
var p = new Point() { X = 100, Y = 200 };
// 顯式調用雙參數構造(參數值被屬性賦值覆蓋)
var p = new Point(10, 20) { X = 100, Y = 200 };
// 最終結果: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 override string ToString() => $"[{X}, {Y}, Color={c}]";
}
// 預設綠色 + 坐標覆蓋
var p1 = new Point(10, 20) { X = 100, Y = 200 }; // Color=Green
// 指定藍色構造 + 坐標覆蓋
var p2 = new Point(PointColor.Blue) { X = 100, Y = 200 }; // Color=Blue
對象初始化器不限於默認構造函數,可顯式調用任意構造函數,構造邏輯(如預設色彩)與屬性賦值(如覆蓋坐標)協同工作。為類型設計多構造函數配合初始化器,能實現極具表達力的「預設 + 覆蓋」初始化模式,代碼意圖清晰、可讀性強。