c# 中的#define灵活控制代码是否编译

语法结构:
#define symbol //在程序的最上方,一行只能定义一个命令
#if symbol
/这里是想要编译的代码/
#elif symbol
/这里是不想要编译的代码/
#endif

#define debug
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ConsoleApplication4
{
    class Program
    {
        public static void Main()
        {
            int a = 4;
            int b = 2;
            //我想运行的代码部分
             #if debug

            Console.WriteLine("测试模式");
            Console.WriteLine("a的值{0}",a);
            Console.WriteLine("b的值{0}", b);

            //我暂时不想运行,又不能删除的代码部分
             #elif debug

             Console.WriteLine("进入else");

             #endif
        }
    }
}

#undefine命令紧跟着#define命令出现,一旦有了它,所有#if symbol和#endif中的代码都不会编译。

#define debug
#undef debug
//加上这句话之后,所有的#if与#endif之间的代码都失效,因为要想进入if + 符号名 = true
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ConsoleApplication4
{
    class Program
    {
        public static void Main()
        {
            int a = 4;
            int b = 2;

             #if debug

            Console.WriteLine("测试模式");
            Console.WriteLine("a的值{0}",a);
            Console.WriteLine("b的值{0}", b);


             #elif debug

             Console.WriteLine("进入else");

            #endif

          Console.WriteLine("#define失效了");


        }
    }
}

比如编写调试程序的代码,在调试阶段可以进行编译,在正式发布版本中,就可以使用预编译器指令禁止编译调试代码。
如果一个系统想发布两个版本,分别是基本版本和有更多功能的企业版本,就可以利用预编译指令来灵活控制是否编译某部分代码

你可能感兴趣的:(c#高老师)