问题
您希望创建泛型类型时,它的类型参数支持指定接口,如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方法的对象。些例中将会引发一个运行期异常。
给泛型指定约束强制类的类型实参进行严格的类型检查,并使得您在编译期发现问题而不是运行期。
阅读参考
查看MSDN文档中的“where Keyword”主题。