跳轉至內容

C# 程式設計/關鍵字/using

來自華夏公益教科書,開放的書籍,造福全世界


在 C# 中,using 關鍵字有兩個完全不相關的含義,取決於它是用作指令還是語句。

using 作為指令解析無限定型別引用,這樣開發者就不必指定完整的名稱空間。

例子

using System;
 
// A developer can now type ''Console.WriteLine();'' rather than ''System.Console.WriteLine()''.

using 還可以為引用型別提供命名空間別名

例子

using utils = Company.Application.Utilities;

using 作為語句會自動呼叫指定物件的 dispose。 該物件必須實現 IDisposable 介面。只要它們是相同型別,就可以在一個語句中使用多個物件。

例子

using (System.IO.StreamReader reader = new StreamReader("readme.txt"))
{
    // read from the file
}
 
// The file readme.txt has now been closed automatically.

using (Font headerFont = new Font("Arial", 12.0f),
            textFont = new Font("Times New Roman", 10.0f))
{
    // Use headerFont and textFont.
}

// Both font objects are closed now.



C# 關鍵字
abstract as base bool break
byte case catch char checked
class const continue decimal default
delegate do double else enum
event explicit extern false finally
fixed float for foreach goto
if implicit in int interface
internal is lock long namespace
new null object operator out
override params private protected public
readonly ref return sbyte sealed
short sizeof stackalloc static string
struct switch this throw true
try typeof uint ulong unchecked
unsafe ushort using var virtual
void volatile while
C# 特殊識別符號(上下文關鍵字)
add alias async await dynamic
get global nameof partial remove
set value when where yield
上下文關鍵字(用於查詢)
ascending by descending equals from
group in into join let
on orderby select where
華夏公益教科書