4.11 在泛型字典类中使用foreach

问题

您希望在实现了System. Collections.Generic.IDictionary接口的类型枚举元素,如System.Collections.Generic.Dictionary System.Collections.Generic.SortedList

解决方案

最简单的方法是在foreach循环中使用KeyValuePair结构体:

C#泛型秘诀(7) // 创建字典对象并填充.
C#泛型秘诀(7)
    Dictionary<intstring> myStringDict = new Dictionary<intstring>();
C#泛型秘诀(7)    myStringDict.Add(
1"Foo");
C#泛型秘诀(7)    myStringDict.Add(
2"Bar");
C#泛型秘诀(7)    myStringDict.Add(
3"Baz");
C#泛型秘诀(7)    
// 枚举并显示所有的键/值对.
C#泛型秘诀(7)
    foreach (KeyValuePair<intstring> kvp in myStringDict)

 

讨论

非泛型类System.Collections.Hashtable (对应的泛型版本为System.Collections.Generic.Dictionary class), System.Collections.CollectionBaseSystem.Collections.SortedList 类支持foreach使用DictionaryEntry类型:

C#泛型秘诀(7)foreach (DictionaryEntry de in myDict)
 

但是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

解决方案

使用约束强制泛型的类型参数实现一个或多个指定接口:

C#泛型秘诀(7)public class DisposableList<T> : IList<T>
C#泛型秘诀(7)        
where T : IDisposable
 

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

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

C#泛型秘诀(7)public static void TestDisposableListCls() 
 

讨论

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方法的对象。些例中将会引发一个运行期异常。

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

阅读参考

查看MSDN文档中的“where Keyword”主题。


相关文章: