且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#中的条件编译

更新时间:2022-09-27 19:35:33

条件编译是C#比Java多出的东西,但我跟前辈请教后,他们都说条件编译在实际的项目开发中不怎么使用.鉴于是新内容,我还是做做笔记,理解一下好了.

  条件编译属于编译预处理的范畴,它能让我们通过条件编译的机制,将部分代码包括进来或者排除出去,其作用与if-else类似.

条件编译指令有以下四种
???? #if
???? #elif
???? #else
???? #endif

  条件编译指令有以下四种

    #if

    #elif

      #else

    #endif

  下面我们通一些例子来说明它们的用法


#define Debug
class Class1
{
 #if Debug
 void Trace(string s) {}
 #endif
}

  执行时由于第一行已经使用#define 指令定义了符号Debug, #if 的条件满足,所以这段代码等同于

 class Class1
{
void Trace(string s) {}
}

  再比如:  

    #define A
 #define B
 #undef C
 class D
{
#if C
void F() {}
#elif A && B
void I() {}
#else
void G() {}
#endif
}

  其编译效果等同于:


class C
{
void I() {}
}

  #if 指令可以嵌套使用, 例如:

C#中的条件编译    #define Debug // Debugging on

 #undef Trace // Tracing off
 class PurchaseTransaction
{
void Commit()
{
#if Debug
CheckConsistency();
#if Trace
WriteToLog(this.ToString());
#endif
#endif
CommitHelper();
}
}

  预编译和条件编译指令还可以帮助我们在程序执行过程中发出编译的错误或警告,相应的指令是#warning 和#error,下面的程序展示了它们的用法:

C#中的条件编译   #define DEBUG

 #define RELEASE
 #define DEMO VERSION
#if DEMO VERSION && !DEBUG
#warning you are building a demo version
#endif
#if DEBUG && DEMO VERSION
#error you cannot build a debug demo version
#endif
 using System;
 class Demo
{
public static void Main()
{
Console.WriteLine(“Demo application”);
}
}

















本文转自cnn23711151CTO博客,原文链接:http://blog.51cto.com/cnn237111/528824 ,如需转载请自行联系原作者