分享

条件编译(含示例代码)

 lhzstudio 2012-05-12

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

#define RELEASE

*/

using System;

using System.Collections.Generic;

using System.Text;

using System.Diagnostics;


namespace ConditionalCombilation

{

    class Program

    {

        static void Main(string[] args)

        {

            #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");

        }

    }

}


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多