本文导读:
- C# 的预处理器指令从来不会转化为可执行代码的命令, 但是会影响编译过程的各个方面, 常用的预处理器指令有 #define,#undef,#if,#elif,#else 和 #endif 等等, 下面介绍 C# 中使用 #define 进行条件编译的实例.
- C# 中条件编译指令用于按条件包含或排除源文件中的某些部分. 在 Visual Studio 中, 会看到被排除的代码显示为灰色.
一,#define 可以用来做什么
1, 当计划发布两个版本的代码的时候. 即基本版和拥有更多版本的企业版, 就可以用到条件编译指令;
2, 例如同一个文件给 silverlight,wpf,winform 等使用, 并且还考虑 Debug 和 Release 等, 有大部分代码是一样的;
3, 指定函数和属性是否编译到最终产品中去.
二,#define 用法
语法:#define 名称
注意: 这里名称取 Debug, 你也可以取其他名称如 Dragon
1 #define Debug
说明:
1,Debug 可以看做是声明的一个变量, 但此变量没有真正的值, 存在时 #if Debug 结果为 true, 否则为 false;
- ,#define 单独用没什么意义, 一般是和 #if 或者 Conditional 特性结合使用;
- ,#define 必须定义在所有 using 命名空间前面;
4,Debug 与 DEBUG 是不同的, C# 区分大小写.
三,#define 条件编译实例
方式一, 使用 #if
- #define Dragon
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Diagnostics;
- namespace ConditionalCompilation
- {
- class Program
- {
- static void Main(string[] args)
- {
- #if Dragon
- Console.WriteLine("Dragon is defined");
- #else
- Console.WriteLine("Dragon is not defined");
- #endif
- Console.ReadKey();
- }
- }
- }
输出结果如下:
如果注释掉 //#define Dragon , 输出结果为:
方式二, 使用 Conditional 特性
我们可以将一些函数隔离出来, 使得它们只有在定义了某些环境变量或者设置了某个值之后才能发挥作用, 使用 Conditional 特性的隔离策略要比 #if/#endif 不容易出错.
- #define Debug
- #define Trace
- #if (Debug && Trace)
- #define DebugAndTrace
- #endif
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Diagnostics;
- namespace ConditionalCompilation
- {
- class Program
- {
- static void Main(string[] args)
- {
- Print0();
- Print1();
- Print2();
- Print3();
- Console.ReadKey();
- }
- [Conditional("DEBUG")]
- static void Print0()
- {
- Console.WriteLine("DEBUG is defined");
- }
- [Conditional("Debug")]
- static void Print1()
- {
- Console.WriteLine("Debug is defined");
- }
- // 定义了 Debug 或者 Trace 后才会执行此方法
- // 或者的关系
- [Conditional("Debug"), Conditional("Trace")]
- static void Print2()
- {
- Console.WriteLine("Debug or Trace is defined");
- }
- // 只有定义了 Debug 和 Trace 后才会执行此方法
- // 并且的关系
- [Conditional("DebugAndTrace")]
- static void Print3()
- {
- Console.WriteLine("Debug and Trace is defined");
- }
- }
- }
输出结果如下:
说明:
1, 代码中没有定义 DEBUG, 却输出了 DEBUG, 是因为 DEBUG 版本, 自动定义了 DEBUG."项目 -- 右键 -- 属性 -- 生成选项卡 -- 常规栏" 下的定义 DEBUG 常量 (U) 前面的复选框被选中. 当然你可以去掉其选中状态, 这样就不会输出 DEBUG 了.
2, 如果 Debug 和 Trace 均没有定义, 则不会输出 Debug or Trace; 只有 Debug 和 Trace 均定义了, 才会输出 Debug and Trace.
3, 可以给 Conditional 增加多个属性如示例代码 [Conditional("Debug"), Conditional("Trace")] , 不过多个属性之间的关系是或的关系, 即 "Debug" 或者 "Trace" 任意一个被定义了, 那么对应方法就会被执行.
4, 如果需要增加多个与的属性, 直接用 Conditional 是无法实现的, 需要借助 #if/#endif 间接来完成, 如示例代码中的组合操作
环境变量 (或条件编译符号) 的设置方法有三:
1)用 #define 定义以及 #undef 取消定义, 在所有 using 命名空间前面定义;
2)用编译器命令行选项 (例如,/define:DEBUG), 在 "项目 -- 右键 -- 属性 -- 生成选项卡 -- 常规栏" 下的条件编译符号(Y) 中设置(如果多个, 可以用英文逗号隔开).DEBUG 版本下, 系统默认设置了 DEBUG 和 TRACE;
3)用操作系统外壳程序中的环境变量(例如, set DEBUG=1).
来源: http://www.bubuko.com/infodetail-3438227.html