實現針對不同.net版本的條件編譯


今天碰到這樣一個需求,寫的C#庫,有時候需要在.net 2.0下編譯,有時候需要在.net 4.0下編譯,這個庫里使用了lambda表達式,使用了擴展方法,使用了幾個 System.Core.dll 引入的Action類型。

為了在 .net 2.0 下能夠編譯成功,我寫了一個文件 Patch.cs,定義了 System.Runtime.CompilerServices.ExtensionAttribute  類型,這樣就可以在2.0下使用lambda表達式和擴展方法了,同時,添加了幾個用到的System.Core.dll 引入的Action類型:

 1:  namespace System.Runtime.CompilerServices
 2:  {
 3:      public class ExtensionAttribute : Attribute { }
 4:  }
 5:  
 6:  namespace System
 7:  {
 8:      public delegate void Action();
 9:      public delegate void Action<T0,T1>(T0 t0,T1 t1);
10:  }
11:  

然而,要在.net 4.0 下編譯,因為類型已經存在,必須注釋掉Patch.cs,很麻煩。於是想通過條件編譯來解決,即:

 1:  #if NET2
 2:  
 3:  namespace System.Runtime.CompilerServices
 4:  {
 5:      public class ExtensionAttribute : Attribute { }
 6:  }
 7:  
 8:  namespace System
 9:  {
10:      public delegate void Action();
11:      public delegate void Action<T0,T1>(T0 t0,T1 t1);
12:  }
13:  
14:  #endif

問題是,.net 里沒有定義和.net版本有關的指示符。怎么辦呢?自己動手,豐衣足食,使用Build Events在編譯之前自動偵測出項目所使用的.net版本,定義出我們想要的指示符。

在  C#模板編程(2): 編寫C#預處理器,讓模板來的再自然一點 一文中,寫了一個程序 Csmacro.exe 來實現C#下的模板機制,本文在Csmacro.exe 的基礎上,增加偵測項目所引用的.net 版本的功能。

原理:查找項目目錄下的 csproj 文件,解析它,找到節點TargetFrameworkVersion,判斷.net版本,然后生成一個Csmacro_Template.cs文件,在里面 #define 版本指示符。例如,對 .Net 2.0 項目,生成的 Csmacro_Template.cs 文件內容為:

#define NET2

修改后Csmacro的代碼可在:https://github.com/xiaotie/GebCommon 上下載(目前只處理了 .net 2.0 和 4.0,如需要針對其它版本,可自行修改代碼)。有了 Csmacro,一切就好辦了。

第一步,把 Csmacro.exe 放在Path路徑下

第二步,打開需要條件編譯的項目,添加 Pre-build 事件:Csmacro.exe $(ProjectDir)

第三步,編輯源文件,如,Patch.cs 文件修改為:

 1:  #region include "Csmacro_Template.cs"
 2:  #endregion
 3:  
 4:  #if NET2
 5:  
 6:  namespace System.Runtime.CompilerServices
 7:  {
 8:      public class ExtensionAttribute : Attribute { }
 9:  }
10:  
11:  namespace System
12:  {
13:      public delegate void Action();
14:      public delegate void Action<T0,T1>(T0 t0,T1 t1);
15:  }
16:  
17:  #endif

#region include 是我引入的 Csmacro 宏語法。詳見 C#模板編程(2): 編寫C#預處理器,讓模板來的再自然一點 一文。點擊編譯,系統會生成一個 Patch_Csmacro.cs 文件,內容如下:

 1:  #define NET2
 2:  
 3:  #if NET2
 4:  
 5:  namespace System.Runtime.CompilerServices
 6:  {
 7:      public class ExtensionAttribute : Attribute { }
 8:  }
 9:  
10:  namespace System
11:  {
12:      public delegate void Action();
13:      public delegate void Action<T0,T1>(T0 t0,T1 t1);
14:  }
15:  
16:  #endif

第四步,把生成的 Patch_Csmacro.cs 添加到項目中來。

搞定以后,選擇不同的target,編譯時產生的就是對該target的條件編譯!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM