C# 析构函数
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
//public class MyTest : IDisposable
//{
// #region IDisposable 成员
// public MyTest()
// {
// }
// public void Dispose()
// {
// Console.WriteLine("IDisposable中");
// }
// #endregion
//}
// class Program
// {
// static void Main(string[] args)
// {
// MyTest temp = null;
// try
// {
// temp = new MyTest();
// Console.WriteLine("Try中");
// //do your processing;
// }
// finally
// {
// if (temp != null) temp.Dispose();
// }
// //using (MyTest temp = new MyTest()) ; //这句可以替掉Try.
// }
// }
public class ResourceHolder : IDisposable
{
private bool isDispose = false;
#region IDisposable 成员
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
protected virtual void Dispose(bool disposing) //派生类才可以访问
{
if (!isDispose)
{
if (disposing)
{
//cleanup managed object by calling the their Disposing method;
}
//cleanup unmanaged objects;
}
isDispose = true;
}
~ResourceHolder() //
{
Dispose(false);
}
public void SomeMethod()
{
//Ensure object not already disposed before exception of any method
if (isDispose)
{
throw new ObjectDisposedException("ResourceHolder");
}
//method implementation...
}
}
public class MainRun
{
static void Main()
{
ResourceHolder temp = new ResourceHolder();
}
}
}