C# 预处理器指令
系统讲解 C# 预处理器指令的书写语法与无宏本质、13 项常用指令清单、#define/#undef 符号控制、#if/#elif/#else/#endif 布尔表达式、#warning/#error/#region/#line/#pragma 与 C# 8.0+ #nullable,并在本地 csc4 实测验证。
学完这一章,你能够
- 系统讲解 C# 预处理器指令的书写语法与无宏本质、13 项常用指令清单、#define/#undef 符号控制、#if/#elif/#else/#endif 布尔表达式、#warning/#error/#region/#line/#pragma 与 C# 8.0+ #nullable,并在本地 csc4 实测验证。
预处理器指令语法特征与 C/C++ 差异
预处理器指令(Preprocessor Directives)用于在正式编译阶段之前向编译器传达条件编译、诊断控制与源码区域标记等指令。所有指令必须以 `#` 开头,同一行内指令前仅允许出现空白字符,且每行只能写一条预处理器指令;由于它们并非普通 C# 语句,末尾绝不能加分号 `;`。与 C/C++ 存在独立文本宏替换预处理器不同,C# 编译器并不提供宏展开机制,预处理器符号仅作为编译期布尔标志用于条件编译。
C# 规范共提供 13 项常见预处理器指令(详见下表),涵盖符号定义与取消(`#define`、`#undef`)、条件编译分支(`#if`、`#elif`、`#else`、`#endif`)、编译期诊断(`#warning`、`#error`)、编辑器代码折叠(`#region`、`#endregion`)、诊断行号映射(`#line`)、特定编译器选项控制(`#pragma`)以及 C# 8.0 新增的可空性上下文控制(`#nullable`)。
#define / #undef 与条件编译表达式
`#define symbol` 用于在当前源文件作用域内定义一个条件编译符号,`#undef symbol` 用于取消已定义符号(二者在 C# 中必须写在源文件最顶部、位于 `using` 与任何代码标记之前)。定义符号后,在 `#if (PI)` 中求值为真,未定义或已被 `#undef` 取消的符号求值为假。本站 `csc4` 实测定义 `PI` 并先定义后取消 `TEMP_SYMBOL`,条件分支准确输出 `PI is defined|TEMP_UNDEF`。
条件编译指令 `#if` / `#elif` / `#else` / `#endif` 构成完整的编译期分支块(每个 `#if` 必须有显式 `#endif` 闭合),条件表达式除测试符号本身外,还支持布尔字面量 `true`/`false`、逻辑非 `!`、相等 `==`、不等 `!=`、逻辑与 `&&`、逻辑或 `||` 及圆括号分组。未命中的分支代码不会参与目标 IL 生成,常用于区分调试版(`DEBUG`)与发布版(`RELEASE`)逻辑。本站实测同时定义 `DEBUG_MODE` 与 `VC_V10` 时准确进入 `DEBUG and VC_V10 are defined` 分支,复合布尔表达式 `((DEBUG_MODE == true) && (TEMP_SYMBOL != true) && (PI || false))` 求值为 `OPS_TRUE`。
诊断、区域折叠、行号重映射与 #pragma 控制
除条件编译外,其余指令分别服务于编译诊断与工程组织:`#warning` 输出自定义编译器警告但不阻断构建,`#error` 直接触发编译错误中止编译(常配合 `#if` 检查非法配置组合);`#region Name` 与 `#endregion` 用于在 IDE 中折叠大段逻辑区块;`#line 100 "MyFile.cs"` 与 `#line default` 改写及恢复编译器诊断信息与 PDB 调试符号报告的文件名和行号(多见于代码生成器;注:在 `csc4` 中 `[CallerLineNumber]` 仍取物理行号);`#pragma warning disable 414` / `#pragma warning restore 414` 则可局部屏蔽并恢复指定编号(如 CS0414 未使用字段)的编译警告。本站实测 `#region`、`#line 100`/`#line default` 及 `#pragma warning disable/restore 414` 均在 `csc4` 下零警告编译通过并正常运行。
工程实践中使用预处理器指令应保持克制:善用 `#region` 辅助分区而非掩盖过长类文件;通过 `#if` 清晰隔离调试诊断与发布配置;利用 `#warning`/`#error` 在编译期及早暴露不兼容的平台符号组合,从而提升代码可维护性与构建安全性。
C# 常用预处理器指令速查表(13 项)
| 预处理器指令 | 功能说明与适用场景 |
|---|---|
| #define | 在文件顶部定义条件编译符号(仅作布尔标志,不做 C 风格文本宏替换) |
| #undef | 在文件顶部取消先前定义的条件编译符号 |
| #if | 开始条件编译块,当符号布尔表达式为真时编译对应分支代码 |
| #elif | 前置 #if/#elif 条件不满足且当前条件为真时编译该分支 |
| #else | 前置所有 #if/#elif 分支均不满足时的兜底编译分支 |
| #endif | 显式结束以 #if 开启的条件编译块 |
| #warning | 在编译输出中生成自定义级别警告信息(不中断编译) |
| #error | 在编译输出中生成自定义错误信息并立即中止编译(可置于 #if 分支守卫配置) |
| #region | 标记可折叠代码区块的起始边界,便于在 IDE 中组织代码 |
| #endregion | 结束与前导 #region 配对的代码折叠区域 |
| #line | 修改或通过 #line default 恢复编译器诊断与调试符号中的行号和文件名 |
| #pragma | 向编译器发出特殊控制指令,最常见用于局部禁用/恢复指定编号警告 |
| #nullable | 启用或禁用 C# 8.0+ 可空引用类型上下文与静态空值警告检查 |
在本地 csc4 实测 #define/#undef、#if/#elif/#else/#endif、#region、#line 与 #pragma
#define PI
#define DEBUG_MODE
#define VC_V10
#define TEMP_SYMBOL
#undef TEMP_SYMBOL
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
namespace CSharpPreprocessorLab
{
internal class Program
{
#pragma warning disable 414
private int unusedDiagnosticField = 42;
#pragma warning restore 414
#region ConditionalHelpers
private static string EvaluateDefineAndUndef()
{
string piStatus;
#if (PI)
piStatus = "PI is defined";
#else
piStatus = "PI is not defined";
#endif
string tempStatus;
#if TEMP_SYMBOL
tempStatus = "TEMP_DEFINED";
#else
tempStatus = "TEMP_UNDEF";
#endif
return piStatus + "|" + tempStatus;
}
private static string EvaluateCompoundConditions()
{
string branch;
#if (DEBUG_MODE && !VC_V10)
branch = "DEBUG_ONLY";
#elif (!DEBUG_MODE && VC_V10)
branch = "VC_V10_ONLY";
#elif (DEBUG_MODE && VC_V10)
branch = "DEBUG and VC_V10 are defined";
#else
branch = "NEITHER";
#endif
string opBranch;
#if ((DEBUG_MODE == true) && (TEMP_SYMBOL != true) && (PI || false))
opBranch = "OPS_TRUE";
#else
opBranch = "OPS_FALSE";
#endif
#if false
#error This error branch is excluded by #if false
#endif
return branch + "|" + opBranch;
}
private static string EvaluateLineDirective()
{
#line 100 "VirtualGenerated.cs"
string markedOutput = "This is line 100";
#line default
string restoredOutput = "Line numbering restored";
return string.Format("{0}|{1}", markedOutput, restoredOutput);
}
#endregion
private static string Esc(string s)
{
if (s == null) return "null";
StringBuilder sb = new StringBuilder("\"");
foreach (char c in s)
{
switch (c)
{
case '\\': sb.Append("\\\\"); break;
case '"': sb.Append("\\\""); break;
case '\n': sb.Append("\\n"); break;
case '\r': sb.Append("\\r"); break;
case '\t': sb.Append("\\t"); break;
default:
if (c < 32) sb.AppendFormat("\\u{0:x4}", (int)c);
else sb.Append(c);
break;
}
}
sb.Append("\"");
return sb.ToString();
}
private static string CaseJson(string name, string summary, string expected, string actual)
{
bool passed = string.Equals(expected, actual, StringComparison.Ordinal);
return string.Format(
"{{\"name\":{0},\"summary\":{1},\"expected\":{2},\"actual\":{3},\"passed\":{4}}}",
Esc(name), Esc(summary), Esc(expected), Esc(actual), passed ? "true" : "false"
);
}
private static void Main(string[] args)
{
Console.OutputEncoding = Encoding.UTF8;
List<string> cases = new List<string>();
// Case 1: #define and #undef
cases.Add(CaseJson(
"define_and_undef_symbols",
"验证文件顶部 #define 定义符号 PI 以及 #undef 取消 TEMP_SYMBOL 后的条件编译分支",
"PI is defined|TEMP_UNDEF",
EvaluateDefineAndUndef()
));
// Case 2: #if / #elif / #else / #endif with !, ==, !=, &&, || and parentheses
cases.Add(CaseJson(
"conditional_if_elif_else",
"验证 #if/#elif/#else/#endif 组合布尔表达式(!、==、!=、&&、|| 与括号分组)的编译期求值",
"DEBUG and VC_V10 are defined|OPS_TRUE",
EvaluateCompoundConditions()
));
// Case 3: #region/#endregion, #line/#line default, and #pragma warning disable/restore 414
Program p = new Program();
string lineInfo = EvaluateLineDirective();
string actual3 = string.Format("{0}|fieldOk={1}", lineInfo, p != null);
cases.Add(CaseJson(
"region_line_and_pragma",
"验证 #region/#endregion 代码折叠区域、#line/#line default 编译通过且正常执行,以及 #pragma warning disable/restore 414",
"This is line 100|Line numbering restored|fieldOk=True",
actual3
));
Console.WriteLine(string.Format(
"{{\"version\":{0},\"cases\":[{1}]}}",
Esc("CLR " + Environment.Version.ToString()),
string.Join(",", cases.ToArray())
));
}
}
}
- 确认 PI/#undef TEMP_SYMBOL 判定、DEBUG_MODE && VC_V10 复合布尔条件以及 #region/#line/#pragma warning disable 414 三组实验零警告编译并全部通过。
所需环境:Windows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。
当前源码 SHA256:9d60072bc3ae316c9c7f453e1cd3242a69e1f7c1418b76ba01cf774393faee18
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、.NET Framework 4.x Visual C# 编译器(csc.exe)本地离线环境。
ZIP SHA256:ebed6c87b04edfca68bb96b54e3daa1a0f37f74bd2fc37c363259433663e8379
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 C# 中编写 `#define PI 3.14159` 并试图用 `PI` 替换数值字面量,为什么无法通过编译?
展开参考解答
因为 C# 没有 C/C++ 的文本宏替换预处理器,`#define` 只能定义不带值的布尔条件符号(`#define PI`)供 `#if` 判断;定义数值常量应使用 `const double PI = 3.14159;`。