.net 2.0 和 4.0不同的.net版本的條件編(biān)譯
今天碰到這樣一個需求,寫的C#庫,有時候需要在.net 2.0下(xià)編(biān)譯,有時候需(xū)要在.net 4.0下編譯,這(zhè)個庫裏使(shǐ)用了lambda表(biǎo)達式,使用了擴展方法(fǎ),使用了幾個 System.Core.dll 引入的Action類型(xíng)。為了在 .net 2.0 下能夠編(biān)譯成功,我寫了一個文件 Patch.cs,定義了 System.Runtime.CompilerServices.ExtensionAttribute 類型,這樣就(jiù)可以在2.0下(xià)使用lambda表達式和擴展(zhǎn)方法了,同時,添加了幾個用到的System.Core.dll 引(yǐn)入的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 下編譯,因為類型已經存在,必(bì)須注釋掉Patch.cs,很麻煩。於是想通過條件編(biān)譯來解決,即:
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 裏沒有定義(yì)和.net版本有關的指示符。怎麽辦(bàn)呢(ne)?自己動手,豐衣(yī)足食,使用Build Events在編譯之前自動偵測出項目(mù)所使用的.net版本,定義出我們想要的指示符(fú)。
在 C#模板編程(2): 編寫C#預處理器,讓模板來的再自然一點 一文中,寫了一個程序(xù) Csmacro.exe 來實現C#下的模板機製,本文在Csmacro.exe 的(de)基礎上,增加偵測項目所引用的.net 版本的(de)功能(néng)。
原理:查找項目目錄下的 csproj 文件,解析它,找到節點TargetFrameworkVersion,判斷.net版本,然後生成一個(gè)Csmacro_Template.cs文件,在裏麵 #define 版本指示符。例如,對 .Net 2.0 項目,生成的(de) Csmacro_Template.cs 文件(jiàn)內容為:
#define NET2
修改後Csmacro的代碼可在:https://github.com/xiaotie/GebCommon 上下載(目前隻處理了 .net 2.0 和 4.0,如需要針對其它版本,可自行修改代碼)。有了 Csmacro,一切(qiē)就好辦了。
第一步,把 Csmacro.exe 放在Path路徑下
第二步,打開(kāi)需要條件(jiàn)編譯的項目,添加 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): 編寫(xiě)C#預處理器(qì),讓模(mó)板來(lái)的再自然一點 一文(wén)。點擊編譯,係統會生成一個 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
第(dì)四步,把生成的 Patch_Csmacro.cs 添加到(dào)項目中來。
搞定以後,選擇不同的target,編譯(yì)時產(chǎn)生的就是對該target的條(tiáo)件編譯!
關鍵詞:.net
閱讀本文後您有什麽感想? 已有 人給出評價!
- 0
- 0
- 0
- 0
- 0
- 0