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”);
    }
    }
    复制代码
  • 相关阅读:
    get请求乱码情况
    write()和prinln()的区别?
    校验码实现
    下载图片代码并且解析乱码
    servlet下根据相对路径找资源
    url-pattern配置
    获取网站资源 getResourceAsStream
    Servlet线程安全性
    http1.1 协议响应方面参数
    HTTP1.1协议请求方面参数
  • 原文地址:https://www.cnblogs.com/martintuan/p/2898782.html
Copyright © 2011-2022 走看看