如何理解针对不同.NET版本的条件编译

发布时间:2021-10-29 16:45:43 作者:柒染
来源:亿速云 阅读:86

本篇文章给大家分享的是有关如何理解针对不同.NET版本的条件编译,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

为了在 .NET 2.0 下能够编译成功,我写了一个文件 Patch.cs,定义了 System.Runtime.CompilerServices.ExtensionAttribute  类型,这样就可以在2.0下使用lambda表达式和扩展方法了,同时,添加了几个用到的System.Core.dll 引入的Action类型:

 namespace System.Runtime.CompilerServices  {      public class ExtensionAttribute : Attribute { }  }  namespace System  {      public delegate void Action();      public delegate void Action<T0,T1>(T0 t0,T1 t1); }

然而,要在.NET 4.0 下编译,因为类型已经存在,必须注释掉Patch.cs,很麻烦。于是想通过条件编译来解决,即:

#if NET2  namespace System.Runtime.CompilerServices  {      public class ExtensionAttribute : Attribute { }  }  namespace System  {     public delegate void Action();     public delegate void Action<T0,T1>(T0 t0,T1 t1); } #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 文件修改为:

 #region include "Csmacro_Template.cs"  #endregion    #if NET2    namespace System.Runtime.CompilerServices  {      public class ExtensionAttribute : Attribute { }  }  namespace System {     public delegate void Action();     public delegate void Action<T0,T1>(T0 t0,T1 t1); }  #endif

#region include 是我引入的 Csmacro 宏语法。详见 C#模板编程(2): 编写C#预处理器,让模板来的再自然一点 一文。点击编译,系统会生成一个 Patch_Csmacro.cs 文件,内容如下:

 #define NET2    #if NET2    namespace System.Runtime.CompilerServices  {      public class ExtensionAttribute : Attribute { }  }   namespace System {     public delegate void Action();     public delegate void Action<T0,T1>(T0 t0,T1 t1); }  #endif

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

搞定以后,选择不同的target,编译时产生的就是对该target的条件编译!

以上就是如何理解针对不同.NET版本的条件编译,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

推荐阅读:
  1. 条件编译使用分析
  2. 如何理解.NET Remoting

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

上一篇:有哪些CSS快速提升技巧

下一篇:Mysql数据分组排名实现的示例分析

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》