2011-01-23 36 views
4

我有從MSDN示例代碼和我發現代碼語法我以前從來沒見過:#如果,#else僞,#endif在C#源代碼

namespace Mvc3RemoteVal.Controllers 
{ 
     public class HomeController : Controller 
     { 
      IUserDB _repository; 

#if InMemDB 
      public HomeController() : this(InMemoryDB.Instance) { } 
#else 
      public HomeController() : this(new EF_UserRepository()) { } 
#endif 


      public HomeController(IUserDB repository) 
      { 
       _repository = repository; 
      } 

      [...] 
     } 

什麼是那些#if#else#endif

什麼是#if InMemDB

什麼是InMemDB?一個變量?

+0

正如其他答案所述,這些在.Net 4.0中並不是新鮮事物,您可能需要知道自C++日子以來它們的存在。 – 2011-01-23 13:15:19

回答

14

這些被稱爲preprocessor directives並自.NET 1.0起存在。它們允許你定義不同的編譯指令,如InMemDB,如果這個變量已被定義,編譯器將評估或不評估塊。 #if directive的文檔提供了更深入的概述。

爲了確定您可以使用/define編譯器選項或在Visual Studio中的項目的屬性的構建標籤使用條件編譯符號變量:

alt text

1

這些不是框架4的新功能

這是您可以用於開發階段和測試的功能: 您可以聲明:

#Define something 

然後

#if something 

全部是 「如果」 將要執行的代碼。所有不是的代碼,都不會。