【C#】using 語法糖拆解研究

  • 12
  • 0
  • C#
  • 2025-09-18

以往自行建立的物件可能要自己new、close跟dispose。自從有了using 陳述句的語法糖,只要把new 包在using 裡面就可以自動消滅,甚至連大括號都不用寫了。於是想要了解語法糖解構之後的實際樣子,以了解運作原理跟使用using 語法糖上需要注意的地方。

首先using 的語法糖要以下的版本才能使用

  • .NET Core 3.0 或更新版本
  • .NET 5 或更新版本

以下有一個使用using 語法糖的範例程式:

public bool Method()
{
    using var obj = new Class();
    obj.DoSomething();
    
    Console.WriteLine("done");
    Console.WriteLine("hello world");
    
    return true;
}

如果還原成有大括號的樣子。要注意的是,using 語法糖會直到Method 執行到最後,要return 時才會dispose。所以不論using 的物件實際作用有多短,都會到return 才dispose。

public void Method()
{
    using(var obj = new Class())
    {
        bool result = obj.DoSomething();
        if(!result)
            return false; // 這邊dispose
        
        Console.WriteLine("done");
        Console.WriteLine("hello world");
        Console.WriteLine("show message");
		
        return true;
    } // 或是這邊才dispose
}

而官方文件提到

 using 陳述式會確保即使在 using 陳述式的區塊內發生例外狀況,也會一併處置可處置的執行個體。

這邊要注意的是:using 只是確保不論發生甚麼事情都會幫你做Dispose,例外還是會被Throw 出來,所以仍需要實作錯誤處理。

將using() 再拆解成不用using 的方式,就如下方程式。

public void Method()
{
    var obj = new Class();
    try
    {
        bool result = obj.DoSomething();
        if(!result)
            return false;

        Console.WriteLine("done");
        Console.WriteLine("hello world");
        Console.WriteLine("show message");
    }
    finally
    {
        if (obj != null)
            obj.Dispose();
    }
}

References
https://learn.microsoft.com/zh-tw/dotnet/csharp/language-reference/statements/using
https://blog.miniasp.com/post/2009/10/12/About-CSharp-using-Statement-misunderstanding-on-try-catch-finally