Skip to content

ZH TW CSharp Directives

Codex edited this page Oct 11, 2026 · 2 revisions

Українська · Русский · English · Deutsch · Français · Italiano · Español · 繁體中文 · 日本語 · 한국어

指令、語言版本和編譯選項

手冊C# · 範例UO

指令開頭為 # 在該行的開頭: #if/#elif/#else/#endif, #define, #undef, #region, #endregion, #warning, #error, #line, #pragma, #nullable。它們控制編譯或診斷。 #region 組織編輯器,但不建立範圍。

簡單範例 (Example.cs)

請將此範例另存為 Example.cs,並與本頁其他範例分開執行。

Example.cs:

// PROJECT-EXAMPLE
#define REPORT
#if REPORT
System.Console.WriteLine("Enabled");
#else
System.Console.WriteLine("Disabled");
#endif

結果:

Enabled
#nullable enable
string? name = null;
UO.Print(name ?? "unknown");
#if DEBUG
UO.Print("Debug configuration");
#else
UO.Print("Regular configuration");
#endif

典型的項目在.csproj中定義了TargetFramework、LangVersion、Nullable、AllowUnsafeBlocks等屬性。語法由編譯器決定,可用的API也由目標平台和相依性決定。

在 C# 的現代功能中,原始字串、集合表達式、主建構子、列表模式、required、進階引用功能、field 的擴展和屬性都很重要。要了解特定版本的確切術語,請使用該語言的官方歷史;預覽功能由單獨的項目參數啟用。

官方文件:指令、語言版本和編譯選項 - Microsoft Learn。

Clone this wiki locally