C#中可使用using关键字自动清除对象资源。
# MyObject.cs
using System;
namespace MyProjects
{
public class MyObject : IDisposable
{
public MyObject()
{
}
public void Dispose ( )
{
// Dispose
Console.WriteLine ( "Disposed" ) ;
// ...
}
}
}
# Class1.cs
using System;
namespace MyProjects
{
public class Class1
{
public Class1()
{
}
public static void Main ( string[] args )
{
using ( MyObject myObject = new MyObject ( ) )
{
Console.WriteLine ( "quit" ) ;
}
}
}
}
使用using会自动调用MyObject的Dispose方法.
如果MyObject未实现IDispose接口,则编译时会出错:无法将类型“MyProjects. MyObject”隐式转换为“System.IDisposable”
这种写法可替代
try
{ //... }
catch
{ }
finnaly
{ MyObject.Dispose ( ) ; }