在程序编译阶段,编译器会自动将using语句生成为try-finally语句,并在finally块中调用对象的Dispose方法,来清理资源。所以,using语句等效于try-finally语句,例如:
using (var s = new StreamReader(path))
{
}
其实等价于
var sr = new StreamReader(path);
try
{
}
finally
{
if (sr != null) ((IDisposable)sr).Dispose();
}
网友评论