Code /*组建必须实现system.ComponentModel.IComponent接口或者继承实现这个接口的类(Component)Component类提供制作组件所需的方法,属性与事件包括释放资源的方法Dispose()取得所属容器的属性Container等Component类中Dispose方法释放资源public void Dispose();protected virtual void Dispose(bool disposing);传入的参数为true时,则释放对象持有资源若为false则只释放其中未受管理的资源。实现一个组件时,复写基础类Dispose(bool)方法,并且在客户端程序代码中调用Dispose(),由这个方法调用传入true的布尔参数,清除所有未受管理以及管理的资源,另外,必须实现析构函数,以在Dispose未被调用时进行未受管理资源的清除工作。 */using System.IO ;using System .Text ;using System .ComponentModel ;using System ;public class PropertyComponent:Component{ private StreamReader myStreamReader; private string strFilePath; public string pFilePath { get{ return strFilePath;} set{strFilePath=value; } } public void DoRead() { if(pFilePath.Length ==0) { Console.WriteLine ("NO File!"); Console.WriteLine ("Don't Excuting"); return; } myStreamReader=new StreamReader (strFilePath); Console.WriteLine ("start read file!"); ReadText(); } private void ReadText() { string strBufferText; try { do { strBufferText=myStreamReader.ReadLine (); Console.WriteLine (strBufferText); }while(strBufferText!=null); } catch(Exception e) { Console.WriteLine (e.ToString ()); } } protected override void Dispose(bool disposing) { if(disposing==true&&strFilePath.Length >0) { Console.WriteLine ("parameters is true"); Console.WriteLine ("close stream object"); myStreamReader.Close (); } base.Dispose (disposing);//释放整个继承结构里所掌握的资源 } ~PropertyComponent() { Console.WriteLine ("Destructor is called"); Console.WriteLine ("Call Dispose(fase)"); Dispose(false); } }class UsingPropComp{ [STAThread ] static void Main(string[] args) { string strReadTextFile; PropertyComponent myPropComp=new PropertyComponent(); Console.WriteLine ("Please Input FilePath:"); strReadTextFile=Console.ReadLine (); myPropComp.pFilePath=strReadTextFile; myPropComp.DoRead(); strReadTextFile=myPropComp.pFilePath; if(strReadTextFile.Length >0) { Console.WriteLine ("readFile:{0}",strReadTextFile); } else { Console.WriteLine ("No Read any File!"); } myPropComp.Dispose(); Console.ReadLine(); }}