?? 使用實現了dispose模式的類型2(更好的方法-使用c#中using).txt
字號:
FileStream 實現了Dispose模式
using 語句只能用于那些實現了IDisposable接口的類型。使用時應謹慎。
下面代碼中段1和段2是等效的。
段2中的using語句使編譯器自動產生try...finally塊,在finally塊中將變量轉型為IDisposable接口,并調用Dispose方法。
using 語句支持相同類型的多個變量及已初始化的變量.
using System;
using System.IO;
namespace TestDisp
{
class Class1
{
/// <summary>
/// 應用程序的主入口點。
/// </summary>
[STAThread]
static void Main(string[] args)
{
Byte[]bytesToWrite=new byte[]{1,2,3,4,5};
//段1---------------------------------
// FileStream fs=null;
// try
// {
// fs=new FileStream("Temp.dat",FileMode.Create);
// fs.Write(bytesToWrite,0,bytesToWrite.Length);
// }
// finally
// {
// if(fs!=null)
// ((IDisposable)fs).Dispose();
// }
//------------------------------------
//段2---------------------------------
using(FileStream fs=new FileStream("Temp.dat",FileMode.Create))
{
fs.Write(bytesToWrite,0,bytesToWrite.Length);
}
//------------------------------------
File.Delete("Temp.dat");
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -