我有一个面向 .NET 3.5 的类库。现在,我想添加一些需要 .NET 4.0 的功能,但我仍然希望能够生成面向 .NET 3.5 的版本(当然没有这些功能)。
理想情况下,我想根据配置定位不同的框架版本:
不幸的是,这似乎是不可能的,因为目标框架对于整个项目来说是全局的......
有办法解决吗?我知道我可以创建包含相同文件的第二个项目,但这对于可维护性来说非常糟糕......
什么是最简单的方法来做到这一点?如果您曾经做过类似的事情,哪种方法效果最好?
最佳答案
首先,您可以从创建条件编译符号开始,该符号使您能够包含或排除仅适用于 .NET4.0 框架的额外功能。
接下来,我认为您必须直接使用 MSBuild,而不是让 VS.NET 构建您的项目。
我曾经做过类似的事情。简而言之,这归结为您必须在 MSbuild 脚本中创建 2 个构建任务。一种允许您为 .NET 3.5 构建项目,另一种允许您构建面向 .NET 4.0 的项目。
在每个构建任务中,您可以定义目标框架和您想要使用的条件编译符号。
构建脚本中的构建任务可能是这样的:
<Target Name="buildall-v4">
<!-- The following ItemGroup defines all the build-constants that have to be used
in the build.
As can be seen, the DEBUG & RELEASE constants are only included when necessary -->
<ItemGroup>
<BuildConstant Include="DEBUG" Condition="'$(buildmode)'=='DEBUG'" />
<BuildConstant Include="RELEASE" Condition="'$(buildmode)'=='RELEASE'" />
<BuildConstant Include="NET_FRAMEWORK_4_0" />
</ItemGroup>
<PropertyGroup>
<BuildConstantsToUse>@(BuildConstant)</BuildConstantsToUse>
</PropertyGroup>
<MSBuild Projects="$(builddir)\Source\MyProject.sln"
Properties="OutputPath=$(outputdir)\v4;Configuration=$(buildmode);DefineConstants=$(BuildConstantsToUse);TargetFrameworkVersion=v4.0" />
</Target>
<Target Name="buildall-v3.5">
<!-- The following ItemGroup defines all the build-constants that have to be used
in the build.
As can be seen, the DEBUG & RELEASE constants are only included when necessary -->
<ItemGroup>
<BuildConstant Include="DEBUG" Condition="'$(buildmode)'=='DEBUG'" />
<BuildConstant Include="RELEASE" Condition="'$(buildmode)'=='RELEASE'" />
</ItemGroup>
<PropertyGroup>
<BuildConstantsToUse>@(BuildConstant)</BuildConstantsToUse>
</PropertyGroup>
<MSBuild Projects="$(builddir)\Source\MyProject.sln"
Properties="OutputPath=$(outputdir)\v3.5\;Configuration=$(buildmode);DefineConstants=$(BuildConstantsToUse);TargetFrameworkVersion=v3.5" />
</Target>
当然,当您想要为 2 个版本构建时,您必须在命令行上单独执行每个 msbuild 命令。
关于.net - 如何在同一项目的不同配置中定位不同的框架版本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9136995/