| 特性 | C / C++ | C# | VB.NET |
|---|---|---|---|
| 定義符號 | #define SYMBOL | #define SYMBOL | #Const SYMBOL = value |
| 定義常數值 | #define MAX 100 | ❌ 不支援 (僅符號) | #Const MAX = 100 |
| 條件編譯 | #if SYMBOL ... #endif | #if SYMBOL ... #endif | #If SYMBOL Then ... #End If |
| 條件判斷值 | #if MAX > 10 | ❌ 僅判斷是否定義 | #If MAX > 10 Then |
| 取消定義 | #undef SYMBOL | #undef SYMBOL | #Const SYMBOL = Nothing |
| 編譯器定義 | -D SYMBOL (GCC/Clang) /D SYMBOL (MSVC) | -define:SYMBOL (csc) 專案屬性 → Build → Conditional compilation symbols | 專案屬性 → Compile → Custom constants |
// 正確:定義符號 (無值、無等號)
#define DEBUG
#define LOGGING_ENABLED
// 錯誤:C# 不支援賦值
// #define DEBUG = true ❌
// #define MAX_COUNT 100 ❌
// 條件編譯區塊
#define TRIAL_VERSION
#if TRIAL_VERSION
public const int MaxUsers = 10;
public const bool EnableExport = false;
#else
public const int MaxUsers = 10000;
public const bool EnableExport = true;
#endif
// 多重條件
#if DEBUG && LOGGING_ENABLED
Console.WriteLine("詳細除錯日誌已啟用");
#elif DEBUG
Console.WriteLine("基本除錯模式");
#endif
不在程式碼寫 #define,改在專案屬性設定,支援多組態切換:
DEBUG;TRACE;MY_FEATURE (分號分隔)優點:原始碼乾淨、CI/CD 易注入、組態隔離。
' 定義常數 (可為數值、字串、布林)
#Const VERSION = "1.2.3"
#Const IS_TRIAL = True
#Const MAX_CONNECTIONS = 50
' 條件編譯區塊
#If IS_TRIAL Then
Public Const MaxUsers As Integer = 10
#Else
Public Const MaxUsers As Integer = 10000
#End If
' 判斷數值
#If MAX_CONNECTIONS > 10 Then
' 程式碼...
#End If
' 區域摺疊 (非條件編譯,僅編輯器)
#Region "資料庫存取層"
' 程式碼...
#End Region
// 傳統:防止重複包含 (Header Guard)
#ifndef MY_HEADER_H
#define MY_HEADER_H
// 宣告...
#endif
// 現代:#pragma once (支援主流編譯器)
#pragma once
// 定義常數值 (建議改用 const/constexpr)
#define PI 3.1415926535 // 預處理器替換,無型別安全
const double PI = 3.1415926535; // 型別安全、有作用域、除錯可見
// 條件編譯平台差異
#if defined(_WIN32) || defined(_WIN64)
#define PLATFORM_WINDOWS
#elif defined(__linux__)
#define PLATFORM_LINUX
#endif
// C# 範例:API 版本相容
#if NETSTANDARD2_0
using HttpClient = System.Net.Http.HttpClient;
#elif NET6_0_OR_GREATER
using HttpClient = System.Net.Http.HttpClient; // 相同但可區分行為
#endif
// 功能開關
#define ENABLE_NEW_UI
public class UIManager
{
public void Render()
{
#if ENABLE_NEW_UI
RenderModernUI();
#else
RenderLegacyUI();
#endif
}
}
// 除錯專用程式碼 (Release 自動移除)
#if DEBUG
public void DumpInternalState() { ... }
#endif
// 靜態分析抑制
#if !CODE_ANALYSIS
[Obsolete("內部使用")]
#endif
internal void InternalMethod() { ... }
#if/#elif/#else/#endif。#If 判斷值。const/constexpr 替代常數宏。