首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# 必懂的 using 與 as 運算子:資源管理與安全型別轉換

     編輯:關於C#

using 與 as 是 C# 中兩個極具實用價值卻常被忽略的語法特性。前者確保資源確定性釋放,後者提供安全的型別轉換。善用它們能寫出更健壯、可讀性更高的程式碼。

1. using 陳述式:確定性資源釋放

基本語法與原理

using 定義一個範圍,範圍結束時自動呼叫物件的 Dispose() 方法(需實作 IDisposable 介面)。編譯器會將其轉換為 try/finally 區塊。

實作範例

// 自訂實作 IDisposable 的類別
public class TestResource : IDisposable
{
    public void Dispose()
    {
        Console.WriteLine("Dispose - 資源已釋放");
    }

    public void DoWork()
    {
        Console.WriteLine("Do a method - 執行工作");
    }
}

// 使用 using 區塊
using (TestResource resource = new TestResource())
{
    resource.DoWork();
}
// 輸出順序:
// Do a method - 執行工作
// Dispose - 資源已釋放

適用場景

  • 資料庫連線(SqlConnection、OracleConnection)
  • 檔案流(FileStream、StreamReader、StreamWriter)
  • 圖形物件(Graphics、Bitmap、Pen、Brush)
  • 網路連線(TcpClient、HttpWebResponse)
  • 任何實作 IDisposable 的非託管資源包裝類別

進階:多重 using 巢狀簡寫

// 巢狀寫法
using (var conn = new SqlConnection(connStr))
using (var cmd = new SqlCommand(sql, conn))
using (var reader = cmd.ExecuteReader())
{
    // ...
}

// C# 8.0+ using 宣告(無需大括號,範圍至方法結束)
using var conn = new SqlConnection(connStr);
using var cmd = new SqlCommand(sql, conn);

2. as 運算子:安全參考型別轉換

語法與等價邏輯

expression as type

// 等價於
expression is type ? (type)expression : (type)null

關鍵差異:轉換失敗時 回傳 null 而非拋出例外。as 僅適用於參考型別與裝箱轉換,值型別(如 int、double)不可使用(除非是可為 null 的值型別 int?)。

實際比較

object[] items = { 123, "test", DateTime.Now, 45.6 };

// ❌ 直接轉型:失敗拋例外
foreach (object o in items)
{
    string s = (string)o; // 第 1、3、4 項會拋 InvalidCastException
    Console.WriteLine(s);
}

// ✅ 使用 as:失敗回傳 null,配合 null 檢查
for (int i = 0; i < items.Length; i++)
{
    string s = items[i] as string;
    if (s != null)
        Console.WriteLine($"{i}: {s}"); // 僅輸出 "1: test"
}

進階模式:as 搭配模式比對(C# 7.0+)

// 傳統寫法
var obj = GetObject();
string str = obj as string;
if (str != null) { /* 使用 str */ }

// 模式比對更簡潔
if (obj is string s) 
{ 
    // 直接使用 s
}

// 甚至可用於 switch
switch (obj)
{
    case string s: /* ... */ break;
    case int i: /* ... */ break;
    case null: /* ... */ break;
}

總結對照表

特性usingas
核心目的資源確定性釋放安全型別轉換
適用對象IDisposable 物件參考型別 / 可為 null 值型別
失敗行為N/A(編譯期保證)回傳 null
常見錯誤忘記 using 導致資源洩漏用於值型別、忽略 null 檢查

將 using 與 as 內化為編碼習慣,能顯著減少資源洩漏與型別轉換例外,是邁向 C# 專業開發者的關鍵步驟。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved