static未央

博客园 首页 新随笔 联系 订阅 管理

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.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”主题。


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();

        }

}

DisposableList只接收实现了IDisposable接口的对象做为它的类型实参。这样无论什么时候,从DisposableList对象中移除一个对象时,那个对象的Dispose方法总是被调用。这使得您可以很容易的处理存储在DisposableList对象中的所有对象。

下面代码演示了DisposableList对象的使用:

    public static void TestDisposableListCls()

    {   

        DisposableList<StreamReader> dl = new DisposableList<StreamReader>();

        // 创建一些测试对象.

        StreamReader tr1 = new StreamReader("c:\\boot.ini");

        StreamReader tr2 = new StreamReader("c:\\autoexec.bat");

        StreamReader tr3 = new StreamReader("c:\\config.sys");

        // 在DisposableList内添加一些测试对象.

       dl.Add(tr1);

        dl.Insert(0, tr2);

        dl.Add(tr3);

        foreach(StreamReader sr in dl)

        {

            Console.WriteLine("sr.ReadLine() == " + sr.ReadLine());

        }

        // 在元素从DisposableList被移除之前将调用它们的Dispose方法

        dl.RemoveAt(0);

        dl.Remove(tr1);

        dl.Clear();

}

讨论

where关键字用来约束一个类型参数只能接收满足给定约束的实参。例如,DisposableList约束所有类型实参T必须实现IDisposable接口:

public class DisposableList<T> : IList<T>

        where T : IDisposable

这意味着下面的代码将成功编译:

DisposableList<StreamReader> dl = new DisposableList<StreamReader>();

但下面的代码不行:

DisposableList<string> dl = new DisposableList<string>();

这是因为string类型没有实现IDisposable接口,而StreamReader类型实现了。

除了一个或多个指定接口需要被实现外,类型实参还允许其他约束。您可以强制类型实参继承自一个指定类,如Textreader类:

public class DisposableList<T> : IList<T>

       where T : System.IO.TextReader, IDisposable

您也可以决定是否类型实参仅为值类型或引用类型。下面的类声明被约束为只使用值类型:

public class DisposableList<T> : IList<T>

          where T : struct

这个类型声明为只能使用引用类型:

public class DisposableList<T> : IList<T>

          where T : class

另外,您也可能会需要一些类型实参实现了公有的默认构造方法:

public class DisposableList<T> : IList<T>

         where T : IDisposable, new()

使用约束允许您编写只接收部分类型实参的泛型类型。如果本节中的解决方案忽略了IDisposable约束,有可能会引发一个编译错误。这是因为并非所有DisaposableList类的类型实参都实现了IDisposable接口。如果您跳过这个编译期检查,DisaposableList对象就可能会包含一个没有公有无参的Dispose方法的对象。些例中将会引发一个运行期异常。

给泛型指定约束强制类的类型实参进行严格的类型检查,并使得您在编译期发现问题而不是运行期。

posted on 2011-12-02 00:15  abstract未央  阅读(418)  评论(0编辑  收藏  举报