110,571
社区成员
发帖
与我相关
我的任务
分享
using (Class1 cls1 = new Class1(), cls2 = new Class1())
{
// the code using cls1, cls2
} // call the Dispose on cls1 and cls2
当在某个代码段中使用了类的实例,而希望无论因为什么原因,只要离开了这个代码段就自动调用这个类实例的Dispose。
要达到这样的目的,用try...catch来捕捉异常也是可以的,但用using也很方便。class Program
{
static void Main(string[] args)
{
//方法1
//using (var context = new TestClass())
//{
// try
// {
// throw new Exception("eee");
// }
// catch (Exception e)
// {
// Console.WriteLine(e);
// //throw e;
// }
//}
//方法2
try
{
using (var context = new TestClass())
{
throw new Exception("eee");
}
}
catch (Exception e)
{
Console.WriteLine(e);
//throw e;
}
Console.ReadLine();
}
}
public class TestClass : System.IDisposable
{
//供程序员显式调用的Dispose方法
public void Dispose()
{
Console.WriteLine("Run Dispose");
//调用带参数的Dispose方法,释放托管和非托管资源
Dispose(true);
//手动调用了Dispose释放资源,那么析构函数就是不必要的了,这里阻止GC调用析构函数
System.GC.SuppressFinalize(this);
}
//protected的Dispose方法,保证不会被外部调用。
//传入bool值disposing以确定是否释放托管资源
protected void Dispose(bool disposing)
{
Console.WriteLine("Run Dispose(" + disposing + ")");
if (disposing)
{
///TODO:在这里加入清理"托管资源"的代码,应该是xxx.Dispose();
}
///TODO:在这里加入清理"非托管资源"的代码
}
//供GC调用的析构函数
~TestClass()
{
Console.WriteLine("Run ~TestClass");
Dispose(false);//释放非托管资源
}
}