C#.NET學(xué)習(xí)筆記5 C#中的條件編譯
更新時間:2012年11月01日 21:41:40 作者:
條件編譯是C#比Java多出的東西,但我跟前輩請教后,他們都說條件編譯在實際的項目開發(fā)中不怎么使用.鑒于是新內(nèi)容,我還是做做筆記,理解一下好了
條件編譯是C#比Java多出的東西,但我跟前輩請教后,他們都說條件編譯在實際的項目開發(fā)中不怎么使用.鑒于是新內(nèi)容,我還是做做筆記,理解一下好了.
條件編譯屬于編譯預(yù)處理的范疇,它能讓我們通過條件編譯的機制,將部分代碼包括進來或者排除出去,其作用與if-else類似.
條件編譯指令有以下四種 #if #elif #else #endif 條件編譯指令有以下四種
#if
#elif
#else
#endif
下面我們通一些例子來說明它們的用法
#define Debug
class Class1
{
#if Debug
void Trace(string s) {}
#endif
}
執(zhí)行時由于第一行已經(jīng)使用#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();
}
}
預(yù)編譯和條件編譯指令還可以幫助我們在程序執(zhí)行過程中發(fā)出編譯的錯誤或警告,相應(yīng)的指令是#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
條件編譯屬于編譯預(yù)處理的范疇,它能讓我們通過條件編譯的機制,將部分代碼包括進來或者排除出去,其作用與if-else類似.
條件編譯指令有以下四種 #if #elif #else #endif 條件編譯指令有以下四種
#if
#elif
#else
#endif
下面我們通一些例子來說明它們的用法
復(fù)制代碼 代碼如下:
#define Debug
class Class1
{
#if Debug
void Trace(string s) {}
#endif
}
執(zhí)行時由于第一行已經(jīng)使用#define 指令定義了符號Debug, #if 的條件滿足,所以這段代碼等同于
復(fù)制代碼 代碼如下:
class Class1
{
void Trace(string s) {}
}
再比如:
復(fù)制代碼 代碼如下:
#define A
#define B
#undef C
class D
{
#if C
void F() {}
#elif A && B
void I() {}
#else
void G() {}
#endif
}
其編譯效果等同于:
復(fù)制代碼 代碼如下:
class C
{
void I() {}
}
#if 指令可以嵌套使用, 例如:
復(fù)制代碼 代碼如下:
#define Debug // Debugging on
#undef Trace // Tracing off
class PurchaseTransaction
{
void Commit()
{
#if Debug
CheckConsistency();
#if Trace
WriteToLog(this.ToString());
#endif
#endif
CommitHelper();
}
}
預(yù)編譯和條件編譯指令還可以幫助我們在程序執(zhí)行過程中發(fā)出編譯的錯誤或警告,相應(yīng)的指令是#warning 和#error,下面的程序展示了它們的用法:
復(fù)制代碼 代碼如下:
#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
相關(guān)文章
一種c#深拷貝方式完勝java深拷貝(實現(xiàn)上的對比分析)
下面小編就為大家?guī)硪黄环Nc#深拷貝方式完勝java深拷貝(實現(xiàn)上的對比分析)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-07-07C#語言基礎(chǔ)——結(jié)構(gòu)體和枚舉類型全面解析
下面小編就為大家?guī)硪黄狢#語言基礎(chǔ)——結(jié)構(gòu)體和枚舉類型全面解析。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-07-07