對象初始化器(Object Initializers)

來源:互聯網
上載者:User

對象初始化器(object initializers)
定義如下類

  public class myclass  {    public int x;    public int y;    public myclass()    {    }    public myclass(int a, int b)    {      x = a;      y = b;    }  }對象初始化器object initializers

建立對象的時候可以使用如下文法:

myclass mc = new myclass() { x = 100, y = 200 };效果等同於

myclass mc = new myclass();mc.x = 100;mc.y = 200;使用預設建構函式時可以省略括弧(resharper也建議省略括弧)

myclass mc = new myclass { x = 100, y = 200 };如果使用帶參數的構造器,初始化參數將被覆蓋,比如下面的代碼,最終x,y的值分別為100,200

myclass mc = new myclass(1, 2) { x = 100, y = 200 };initializing inner types

略,參考相關資料

 

集合初始化器(collection initializers):

可以使用類似初始化數組的文法初始化集合類, {}內的內容添加為集合成員,和數組初始化不一樣的是必須顯式調用建構函式

arraylist al = new arraylist(){1, 2, 3, 4};  //okarraylist al = new arraylist{1, 2, 3, 4};  //okarraylist al = { 1, 2, 3, 4 };    //compile failed應用範圍:使用這種方式初始化的類必須實現了ienumerable介面,同時必須定義了名為add的方法,並且add方法的形參列表必須與初始化時的實參一致。

  public class someclass : ienumerable  {    public void add(int i)    {      console.writeline("add value {0}", i);    }    public void add(int i, string s)    {      console.writeline("add value {0}, {1}", i, s);    }    public ienumerator getenumerator()    {      return null;  //不影響初始化    }  }  someclass a = new someclass { 1, 2, 3};  //ok  someclass b = new someclass { {1, "aa"}, {2, "bb"}, {3,"cc"} }; //ok, 初始化dictionary使用類似的文法  someclass c = new someclass { "aa", "bb", "cc" }; //compile failed

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.