ExtensionAttribute类型,这样就可以在2.0下使用lambda表达式和扩展方法了,同时,添加了几个用到的System.Core.dll引入的Action类型。下面学步园小编来讲解下怎样实现针对不同.net版本的条件编译?
怎样实现针对不同.net版本的条件编译
1.namespaceSystem.Runtime.CompilerServices
2.{
3.publicclassExtensionAttribute:Attribute{}
4.}
5.namespaceSystem
6.{
7.publicdelegatevoidAction();
8.publicdelegatevoidAction
9.}
然而,要在.net4.0下编译,因为类型已经存在,必须注释掉Patch.cs,很麻烦.于是想通过条件编译来解决,即:
1.#ifNET2
2.3.namespaceSystem.Runtime.CompilerServices
4.{
5.publicclassExtensionAttribute:Attribute{}
6.}
7.8.namespaceSystem
9.{
10.publicdelegatevoidAction();
11.publicdelegatevoidAction
12.}
13.14.#endif
问题是,.net里没有定义和.net版本有关的指示符.怎么办呢?自己动手,丰衣足食,使用BuildEvents在编译之前自动侦测出项目所使用的.net版本,定义出我们想要的指示符.
在C#模板编程(2):编写C#预处理器,让模板来的再自然一点一文中,写了一个程序Csmacro.exe来实现C#下的模板机制,本文在Csmacro.exe的基础上,增加侦测项目所引用的.net版本的功能.
原理:查找项目目录下的csproj文件,解析它,找到节点TargetFrameworkVersion,判断.net版本,然后生成一个Csmacro_Template.cs文件,在里面#define版本指示符.例如,对.Net2.0项目,生成的Csmacro_Template.cs文件内容为:
#defineNET2
修改后Csmacro的代码可在:https://github.com/xiaotie/GebCommon上下载(目前只处理了.net2.0和4.0,如需要针对其它版本,可自行修改代码).有了Csmacro,一切就好办了。
怎样实现针对不同.net版本的条件编译
第一步,把Csmacro.exe放在Path路径下
第二步,打开需要条件编译的项目,添加Pre-build事件:Csmacro.exe$(ProjectDir)
第三步,编辑源文件,如,Patch.cs文件修改为:
1.#regioninclude“Csmacro_Template.cs”
2.#endregion
3.#ifNET2
4.5.namespaceSystem.Runtime.CompilerServices
6.{
7.publicclassExtensionAttribute:Attribute{}
8.}
9.10.11.namespaceSystem
12.{
13.publicdelegatevoidAction();
14.publicdelegatevoidAction
15.}
16.17.#endif
#regioninclude是我引入的Csmacro宏语法.点击编译,系统会生成一个Patch_Csmacro.cs文件,内容如下:
1.#defineNET2
2.3.#ifNET2
4.5.namespaceSystem.Runtime.CompilerServices
6.{
7.publicclassExtensionAttribute:Attribute{}
8.}
9.10.namespaceSystem
11.{
12.publicdelegatevoidAction();
13.publicdelegatevoidAction
14.}
15.16.#endif
第四步,把生成的Patch_Csmacro.cs添加到项目中来.
搞定以后,选择不同的target,编译时产生的就是对该target的条件编译!
以上就是关于“怎样实现针对不同.net版本的条件编译”的内容,希望对大家有用。更多资讯请关注学步园。学步园,您学习IT技术的优质平台!