using 是 C# 中極少數擁有三種完全不同語義的關鍵字之一。掌握其三重身份,能寫出更整潔、安全、可維護的代碼。
using System;
using System.Collections.Generic;
using System.Linq;
using(VS 提供「移除並排序」功能),減少 IntelliSense 污染。using MySql = MySql.Data.MySqlClient;
using PgSql = Npgsql;
// 使用
var conn1 = new MySql.MySqlConnection();
var conn2 = new PgSql.NpgsqlConnection();
using StringIntDict = System.Collections.Generic.Dictionary;
using AsyncTask = System.Threading.Tasks.Task;
// 使用
var map = new StringIntDict();
AsyncTask task = ComputeAsync();
using WinForms = System.Windows.Forms;
using Wpf = System.Windows.Controls;
// 明確區分
var btn1 = new WinForms.Button();
var btn2 = new Wpf.Button();
所有實作 IDisposable 的物件(檔案流、資料庫連線、GDI+ 物件、非托管記憶體)都應包裹在 using 區塊中。
using (var fs = new FileStream("data.bin", FileMode.Open))
using (var reader = new BinaryReader(fs)) {
var data = reader.ReadBytes(1024);
// 區塊結束自動呼叫 reader.Dispose() → fs.Dispose()
}
FileStream fs = new FileStream("data.bin", FileMode.Open);
try {
BinaryReader reader = new BinaryReader(fs);
try {
var data = reader.ReadBytes(1024);
}
finally {
if (reader != null) ((IDisposable)reader).Dispose();
}
}
finally {
if (fs != null) ((IDisposable)fs).Dispose();
}
關鍵點:即使區塊內拋出異常,finally 仍保證 Dispose() 被調用,且 null 檢查避免二次異常。
using var fs = new FileStream("data.bin", FileMode.Open);
using var reader = new BinaryReader(fs);
// 方法結束時自動 Dispose,無需大括號嵌套
| 誤區 | 正確做法 |
|---|---|
| using 可用於任意類別 | 類別必須實作 IDisposable,否則編譯錯誤 |
| using 區塊內可重新指派變數 | 變數隱含 readonly,不可重新指派 |
| 多個不同類型可共用一個 using | 每個 using 只能管理一個資源宣告(C# 8.0 前) |
| Dispose() 等同於解構子 | Dispose 為顯式釋放,Finalizer 為 GC 最後防線,兩者互補 |
public class DbTransactionScope : IDisposable {
private readonly SqlTransaction _tx;
public DbTransactionScope(SqlConnection conn) {
_tx = conn.BeginTransaction();
}
public void Commit() => _tx.Commit();
public void Dispose() {
if (_tx.Connection != null) _tx.Rollback(); // 未 Commit 則回滾
_tx.Dispose();
}
}
// 使用
using (var scope = new DbTransactionScope(conn)) {
ExecuteBusinessLogic(scope);
scope.Commit(); // 正常完成才提交
}
Dispose() 執行,是 C# 資源管理的基石。善用三重身份,代碼更簡潔、資源更安全、協作更順暢。