多个CS文件复用namespace前置条件编译代码的正确方法
多CAD平台条件编译引用复用方案
方案1:C# 10/.NET 6+ 全局Using方案(推荐)
该方案是当前最高效的实现方式,无需修改项目配置,仅需新增一个全局引用文件即可:
- 在项目根目录新建命名为
GlobalUsings.cs的代码文件 - 将原条件编译代码中的所有
using声明前添加global修饰符,写入该文件即可,示例如下:
#if ACAD global using Autodesk.AutoCAD.Runtime; global using _AcGe = Autodesk.AutoCAD.Geometry; global using _AcAp = Autodesk.AutoCAD.ApplicationServices; global using _AcDb = Autodesk.AutoCAD.DatabaseServices; global using _AcEd = Autodesk.AutoCAD.EditorInput; global using _AcGi = Autodesk.AutoCAD.GraphicsInterface; global using _AcClr = Autodesk.AutoCAD.Colors; global using _AxApp = AutoCAD; #endif #if BCAD global using Teigha.Runtime; global using _AcTrx = Teigha.Runtime; global using _AcGe = Teigha.Geometry; global using _AcAp = Bricscad.ApplicationServices; global using _AcDb = Teigha.DatabaseServices; global using _AcEd = Bricscad.EditorInput; global using _AcGi = Teigha.GraphicsInterface; global using _AcClr = Teigha.Colors; global using _AxApp = BricscadApp; // COM global using _AxDb = BricscadDb; // COM global using Teigha.DatabaseServices; global using Teigha.Geometry; #endif #if ZCAD global using ZwSoft.ZwCAD.Runtime; global using _AcTrx = ZwSoft.ZwCAD.Runtime; global using _AcGe = ZwSoft.ZwCAD.Geometry; global using _AcAp = ZwSoft.ZwCAD.ApplicationServices; global using _AcDb = ZwSoft.ZwCAD.DatabaseServices; global using _AcEd = ZwSoft.ZwCAD.EditorInput; global using _AcGi = ZwSoft.ZwCAD.GraphicsInterface; global using _AcClr = ZwSoft.ZwCAD.Colors; global using _AxApp = ZWCAD; // COM #endif
配置完成后,整个项目内所有CS文件都会自动生效这些引用和别名定义,和手动复制到每个文件开头的效果完全一致,条件编译逻辑也会跟随项目设置的编译符号正常生效。
方案2:低版本C#/.NET兼容方案
如果使用的是C# 9及更低版本(.NET 5及更早框架),可以通过强制导入文件的方式实现:
- 项目根目录新建命名为
CadUsings.cs的代码文件,直接写入你原有的全部条件编译代码,不需要添加额外修饰符 - 项目根目录新建
Directory.Build.props配置文件,写入如下内容:
<Project> <ItemGroup> <Compile Include="CadUsings.cs" Visible="false" /> </ItemGroup> <PropertyGroup> <ForcedIncludeFiles>$(MSBuildThisFileDirectory)CadUsings.cs</ForcedIncludeFiles> </PropertyGroup> </Project>
该配置会让编译器自动将CadUsings.cs的内容插入到所有CS文件的最开头,完全复现手动复制的效果,兼容所有.NET框架版本。如果需要多个项目共用该配置,将两个文件放到解决方案根目录即可,所有子项目会自动继承配置。
内容的提问来源于stack exchange,提问作者Andrew Truckle
相关产品推荐
相关产品推荐

