C#泛型(9)--在泛型字典类中使用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.CollectionBaseSystem.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”主题。

共有0个回答