C# 6.0:新的Dictionary Initializer

來源:互聯網
上載者:User

標籤:style   blog   http   ar   io   color   os   使用   sp   

初始化Dictionary不是什麼新東西,你可以簡單的通過Collection Initializer來初始化一個Dictionary,這是從C#3.0就有的特性。Collection Initializer添加一個參數做key,一個參數作為對應key的value。C#6.0添加了一種在初始化中使用Key/indexer來將value直接映射key和value的能力。

下面的代碼顯示了Collection Initializer是怎樣初始化Dictionary的。

Dictionary<int, string> students = new Dictionary<int, string> {    {1, "Student 1" },    {2, "Student 2" },    {3, "Student 3" },    {4, "Student 4" }};
View Code

這會定義一個名為students的Dictionary對象,它有一個Key為int類型的students列表,如所示:

在C# 6.0種,使用新的Dictionary Initializer,下面的代碼塊也會實現同樣的功效:

Dictionary<int, string> students = new Dictionary<int, string> {    [1] = "Student 1" ,    [2] = "Student 2",    [3] = "Student 3",    [4] = "Student 4",};
View Code

上面的代碼返回同樣的結果,不同的是它們的賦值方法。在C#6.0中,看起來我們是通過indexer來獲得它們。而這使代碼變得更好理解。

現在,如果你想要給collection中添加新元素的話你可以使用下面的方法。

students[5] = "Student 5";students[6] = "Student 6";

上面的代碼會在dictionary中添加兩個新的元素。

C# 6.0:新的Dictionary Initializer

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.