Skip to content

ZH TW CSharp Directive Error

Codex edited this page Oct 11, 2026 · 2 revisions

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

明顯的編譯錯誤

使用手冊C# · 實用指南

如果指令屬於活動分支,則停止編譯並出現作者錯誤。這些例子顯示了故意拒絕的條件。

簡單範例 (Example.cs)

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

Example.cs:

// PROJECT-EXAMPLE
#define CONFIGURED
#if !CONFIGURED
#error Missing configuration
#endif
System.Console.WriteLine("Configured");

此範例可編譯:已定義 CONFIGURED,所以 #error 分支未啟用。下方刻意無法編譯的範例仍保留標示。

結果:

Configured

句法

#error message

這些範例故意不編譯。設定所需的配置後,刪除錯誤或將其移至非活動分支。

**狀態:故意編譯錯誤。 **

範例1

#error Missing required configuration
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)
    {
        Console.WriteLine("Never reached");
    }
}

範例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)
    {
        #if !CONFIGURED
        #error Define CONFIGURED before compiling
        #endif
        Console.WriteLine("Configured");
    }
}

官方來源:Microsoft學習。

Clone this wiki locally