首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 3.0 對象與集合初始化器詳解(四):自定義構造函數調用、Point 擴展色彩屬性、集合初始化器規則

     編輯:關於C語言

對象初始化器中調用自定義構造函數


var p = new Point() { X = 100, Y = 200 };        // 默認構造
var p = new Point(10, 20) { X = 100, Y = 200 }; // 自定義構造:參數被忽略,屬性賦值生效

擴展 Point:增加色彩屬性與構造函數


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 調用。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved