C#泛型秘訣(7)

來源:互聯網
上載者:User

4.11 在泛型字典類中使用foreach

問題

您希望在實現了System. Collections.Generic.IDictionary介面的類型枚舉元素,如System.Collections.Generic.Dictionary 或 System.Collections.Generic.SortedList。

解決方案

最簡單的方法是在foreach迴圈中使用KeyValuePair結構體:

// 建立字典對象並填充.
  Dictionary<int, string> myStringDict = new Dictionary<int, string>();
  myStringDict.Add(1, "Foo");
  myStringDict.Add(2, "Bar");
  myStringDict.Add(3, "Baz");
  // 枚舉並顯示所有的鍵/值對.
  foreach (KeyValuePair<int, string> kvp in myStringDict)
  {
    Console.WriteLine("key  " + kvp.Key);
    Console.WriteLine("Value " + kvp.Value);
}

討論

非泛型類System.Collections.Hashtable (對應的泛型版本為System.Collections.Generic.Dictionary class), System.Collections.CollectionBase和System.Collections.SortedList 類支援在foreach使用DictionaryEntry類型:

foreach (DictionaryEntry de in myDict)
  {
    Console.WriteLine("key " + de.Key);
    Console.WriteLine("Value " + de.Value);
}

但是Dictionary對象支援在foreach迴圈中使用KeyValuePair<T,U>類型。這是因為GetEnumerator方法返回一個Ienumerator,而它依次返回KeyValuePair<T,U>類型,而不是DictionaryEntry類型。

KeyValuePair<T,U>類型非常合適在foreach迴圈中枚舉泛型Dictionary類。DictionaryEntry類型包含的是鍵和值的object對象,而KeyValuePair<T,U>類型包含的是鍵和值在建立一個Dictionary對象是被定義的原本類型。這提高了效能並減少了代碼量,因為您不再需要把鍵和值轉化為它們原來的類型。

閱讀參考

查看MSDN文檔中的“System.Collections.Generic.Dictionary Class”、“System.Collections.Generic. SortedList Class”和“System.Collections.Generic.KeyValuePair Structure”主題。

4.12型別參數的約束

問題

您希望建立泛型型別時,它的型別參數支援指定介面,如IDisposable。

解決方案

使用約束強制泛型的型別參數實現一個或多個指定介面:

public class DisposableList<T> : IList<T>
    where T : IDisposable
  {
    private List<T> _items = new List<T>();
    // 用於釋放列表中的項目的私人方法
    private void Delete(T item)
    {
      item.Dispose();
    }
}

聯繫我們

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