在C#中我們還是很有必要掌握using關鍵字的。
比如這樣:
string path = “D:\data.txt”;
if (!File.Exists(path ))
{File.Create(path); File.WriteAllText(path,"OK");
}
首先我創建一個文件,然后就寫數據入文件中,邏輯看起來沒錯,但是運行起來,就報錯了:IOException: The process cannot access the file 'D:\data.txt' because it is being used by another process.
提示進程正被占用。毫無疑問是我們創建了文件,但是沒有釋放資源,程序就判斷你的資源被占用了。
不懂用using關鍵字的就感覺比較麻煩了,但是通過使用using,輕松解決。
string path = “D:\data.txt”;
if (!File.Exists(path ))
{using(File.Create(path)){File.WriteAllText(path,"OK");} }
事實上using還是有不少用處的。
1、首先是上面案例:它可以管理資源,它會自動釋放實現了IDisposable接口的對象,這樣可以確保在使用完對象后,及時釋放相關資源,避免內存泄漏。事實上,它除了處理一個資源外,它還可以同時處理多個資源,通過逗號分開就行,例如:
using (var stream = new FileStream("file.txt", FileMode.Open))
{// 使用stream對象進行文件操作// 在代碼塊結束時,stream會自動調用Dispose()方法釋放資源
}using (var stream1 = new FileStream("file1.txt", FileMode.Open),stream2 = new FileStream("file2.txt", FileMode.Open))
{// 使用stream1和stream2進行文件操作// 在代碼塊結束時,兩個流對象的資源會被自動釋放
}
2、引入命名空間:這個就比較常見了。如:
using System;
using System.IO;namespace MyNamespace
{class MyClass{static void Main(){// 可以直接使用Console和File類,而無需寫成System.Console和System.IO.FileConsole.WriteLine("Hello, world!");File.WriteAllText("file.txt", "Hello!");}}
}
3、可以使用using static導入靜態類的成員。
using static MyNamespace.MathHelper;namespace MyNamespace
{static class MathHelper{public static int Add(int a, int b){return a + b;}}class MyClass{static void Main(){int result = Add(3, 4); // 直接使用Add方法,無需寫成MathHelper.Add}}
}
4、使用別名來簡化長命名空間的使用。
比如我覺得System.IO這個命名空間有點長,那么我使用using SysIO =?System.IO代替它。
5、自定義類型的資源管理.:當我們編寫的自定義類型需要進行資源管理,就可以通過實現IDisposable接口,并在Dispose方法中釋放相關資源。這樣該自定義類型就可以像標準類型一樣使用using語句塊進行資源管理。如自定義類:
public class MyResource : IDisposable
{private bool disposed = false;// 實現IDisposable接口的Dispose方法public void Dispose(){Dispose(true);GC.SuppressFinalize(this);}protected virtual void Dispose(bool disposing){if (!disposed){if (disposing){// 釋放托管資源}// 釋放非托管資源disposed = true;}}// 如果有非托管資源,還可以實現析構函數(Finalize方法)~MyResource(){Dispose(false);}
}
使用:
using (var resource = new MyResource())
{// 使用resource對象// 在代碼塊結束時,resource對象的資源會被自動釋放
}
6、除此意外,我們還可以結合try~catch語句,捕捉異常。如:
try
{using (var resource = new MyResource()){// 使用resource對象// 可能會拋出異常}
}
catch (Exception ex)
{// 處理異常
}
上面案例中,當發生異常時using語句塊會自動調用Dispose方法釋放資源,然后異常會被捕獲然后在catch塊中進行處理。