在C#中,有两种进行条件编译的方法: 。预处理用法 。条件属性
#define DEBUG 这样定义了符号DEBUG,且范围在它所定义的文件内。请注意,必须要先定义符号才能使用其它语句。例如,以下代码段是不正确的: using System; #define DEBUG 你也可以使用编译器定义符号(用于所有的文件): csc /define:DEBUG mysymbols.cs 如果你想用编译器定义多种符号,只需用分号隔开它们: csc /define:RELEASE;DEMOVERSION mysymbols.cs 在C#源文件中,对这两种符号的定义分为两行 #define 标志。
你也可以使用逻辑“与”(&&)、逻辑“或”(||)以及“否”(!) #define DEBUG #define RELEASE #define DEMOVERSION
#if DEMOVERSION && !DEBUG #warning You are building a demo version #endif
#if DEBUG && DEMOVERSION #error You cannot build a debug demo version #endif
//在解决方案的属性-生成中,也有相关的条件编译符号定义 //所以不能直接注释掉DEBUG,定义REALEASE
#define DEBUG /* #if DEBUG #undef DEBUG #endif */ using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; namespace ConditionalCombilation { class Program { static void { #if DEBUG Console.WriteLine("DEBUG"); #elif RELEASE Console.WriteLine("RELEASE"); #endif OutTime(15); Console.ReadLine(); } [Conditional("DEBUG")] private static void OutTime(int timetake) { Console.WriteLine(timetake.ToString() + "ms used"); } } } |
|