ZH TW CSharp Keyword using - LIHACHTETAN/ClassicUO-Bad-Newbie-CSharp-Scripts-IDE GitHub Wiki
Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어
C#: using
匯入名稱、設定別名或管理 IDisposable/IAsyncDisposable 資源。導入本身不會新增缺少的依賴項。
簡單範例 (Example.cs)
請將此範例另存為 Example.cs,並與本頁其他範例分開執行。
Example.cs:
// PROJECT-EXAMPLE
using System;
using (var stream = new System.IO.MemoryStream())
{
stream.WriteByte(65);
Console.WriteLine(stream.Length);
}
結果:
1
句法
using Namespace; / using Alias = Type; / using var resource = ...; / await using ...;
using 聲明在作用域結束前一直有效。對於 .csx,如果頂級聲明對於腳本語法不明確,請使用 using (...) { ... } 。
例1:基本形式
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
public static class Program
{
public static async Task Main(string[] args)
{
using var stream = new MemoryStream();
stream.WriteByte(65);
Console.WriteLine(stream.Length);
}
}
例2:另一種實用形式
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
public static class Program
{
public static async Task Main(string[] args)
{
await using var stream = new MemoryStream();
await stream.WriteAsync(new byte[] { 1, 2, 3 });
Console.WriteLine(stream.Length);
}
}
官方來源:Microsoft學習。