条件编译是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 指令可以嵌套使用, 例如:
实现代码如下:

#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,下面的程序展示了它们的用法:
实现代码如下:

#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”);
    }
  }

作者:notifier

以上就是【C#.NET学习笔记5 C#中的条件编译】的全部内容了,欢迎留言评论进行交流!

赞(0) 踩(0)

与本文相关的软件

发表我的评论

最新评论

  1. 暂无评论