zoukankan      html  css  js  c++  java
  • C#中的条件编译

    条件编译是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
    {
    publicstaticvoid Main()
    {
    Console.WriteLine(“Demo application”);
    }
    }
    复制代码
  • 相关阅读:
    python笔记26(正则表达式、re模块)
    python笔记24(回顾、复习)
    python笔记25(正则表达式课程一)
    python笔记23(面向对象课程五)
    python(leetcode)-1.两数之和
    python(leetcode)-283移动零
    python(leetcode)-66加一问题
    python(leetcode)-350两个数组的交集
    python(leetcode)-136只出现一次的数字
    python数据结构-数组/列表/栈/队列及实现
  • 原文地址:https://www.cnblogs.com/martintuan/p/2898782.html
Copyright © 2011-2022 走看看