C# 使用Conditional特性而不是#if條件編譯

來源:互聯網
上載者:User

標籤:

      概述

    #if/#endif 語句常用來基於同一份源碼產生不同的編譯結果,其中最常見的就是debug版和release版。但是這些工具在實際應用中並不是非常友好,因為它們容易被濫用,其字碼頁進而難以理解或調試。C#設計中考慮到這個問題,並提供了更好的工具——Conditional特性,用來為不同的環境編譯不同的機器碼。Conditional特性適用於方法的層面,這將強制我們將條件代碼拆分為獨立的方法。在需要編寫條件代碼時,我們應該使用Conditional特性來替代#if/#endif。

      功能描述

使用#if/#endif 語句的缺點

  例如編寫一個私人方法來擷取調用它的函數名稱:

private string CheckMethod()        {#if DEBUG            Trace.WriteLine("Entering CheckState for Person");            string methodName = new StackTrace().GetFrame(1).GetMethod().Name;            return methodName;#endif            return null;        }
更好的解決辦法——使用Conditional特性

  為了避免出現上面的問題我們可以使用Conditional特性。使用Conditional特性即可將一些函數拆分出來,讓其只有在定義了某些環境變數或者設定了某個值之後才能編譯並成為類的一部分。Conditional特性最常用的地方就是講一段代碼變成調試語句。使用Conditional特性的隔離策略要比#if/#endif不容易出錯。

看下面的代碼:

       [Conditional("DEBUG")]        private void CheckMethod()        {            Trace.WriteLine("Entering CheckState for Person");            string methodName = new StackTrace().GetFrame(1).GetMethod().Name;        }
Conditional特性的限制

Conditional特性只可以應用在整個方法上。

任何使用了Conditional特性的方法都只能返回void類型。

      功能擴充

我們可以配置解決方案檔案,來決定編譯時間候啟動並執行代碼,流程如下:

1、配置解決方案資訊:

 

2、編寫代碼約束:

    [Conditional("IN_MEMORY")]        private static void ConfigureInMemory()        {            ................................................                   }        [Conditional("NHIBERNATE")]        private static void ConfigureInMemory()        {
      ................................................
     }

 

代碼產生的時候,我們就可以根據Conditional來決定編譯走的流程;

 

C# 使用Conditional特性而不是#if條件編譯

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.