我想在我的 Visual Studio Microsoft.NET.Sdk 项目中支持多个 TargetFrameworks,但我想制作它以便我有几个解决方案,其中解决方案将确定它将编译哪个目标框架。
理论上,这可以像这样完成:
Directory.Build.props:
<Project>
<!--
TargetFramework is not defined at nuget restore phase - but we can define it.
If solution name contains "netcore" - then solution aims to .net core.
-->
<PropertyGroup Condition="$(SolutionName.Contains('netcore'))">
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<PropertyGroup Condition="!$(SolutionName.Contains('netcore'))">
<TargetFramework>net472</TargetFramework>
</PropertyGroup>
<PropertyGroup>
<!-- nuget restore path must be different for different target frameworks, otherwise it will create mess between projects -->
<BaseIntermediateOutputPath>$(MSBuildThisFileDirectory)obj\nuget\$(TargetFramework)\$(MSBuildProjectName)\</BaseIntermediateOutputPath>
</PropertyGroup>
</Project>
然后有两种解决方案,一种用于 .net framework 4.7.2,一种用于 .net core,其中第二个解决方案文件名应包含“netcore”字符串。
但是,如果TargetFramework
开始在netstandard2.0
诸如此类之间发生变化,这将无法正常工作...
然后我想到 - 也许我可以为多个框架执行 nuget restore,但只是为一个框架编译项目。我认为BeforeBuild
事件可用于区分 nuget restore 和 build 之间的构建阶段 - 所以我写了这样的东西:
test.csproj:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFrameworks>netcoreapp3.1;net472</TargetFrameworks>
</PropertyGroup>
<Target Name="BeforeBuild">
<PropertyGroup>
<TargetFrameworks>net472</TargetFrameworks>
</PropertyGroup>
<Message Text="TargetFrameworks: $(TargetFrameworks)" />
</Target>
但这不起作用,构建发生在两个框架上,而不是一个,就像我最初想要的那样。
当然BeforeBuild
最终应该执行解决方案,这netcore
在它的名字中是没有的。
也许有人可以为此提出更好的解决方案?
想通了。
所以多个解决方案不会容忍彼此的存在,并且需要覆盖nuget restore目录。覆盖可以根据解决方案进行,只是为了简单起见 - 只需使用解决方案名称来定义 nuget 还原路径。
Directory.Build.props:
<Project>
<PropertyGroup>
<BaseIntermediateOutputPath>$(MSBuildThisFileDirectory)obj\nuget\$(SolutionName)\$(MSBuildProjectName)\</BaseIntermediateOutputPath>
</PropertyGroup>
</Project>
然后各个项目确定他们想要使用的目标框架,例如:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
</PropertyGroup>
<PropertyGroup Condition="$(SolutionName.Contains('netcore'))">
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<PropertyGroup Condition="!$(SolutionName.Contains('netcore'))">
<TargetFramework>net472</TargetFramework>
</PropertyGroup>
<PropertyGroup>
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
<IntermediateOutputPath>$(SolutionDir)obj\$(TargetFramework)-$(Configuration)\$(AssemblyName)\</IntermediateOutputPath>
<OutputPath>$(SolutionDir)bin\$(TargetFramework)-$(Configuration)</OutputPath>
</PropertyGroup>
<ItemGroup>
<Compile Remove="obj\**" />
<EmbeddedResource Remove="obj\**" />
<None Remove="obj\**" />
</ItemGroup>
</Project>
这将允许有单独的解决方案,每个目标框架一个,但也可以正常用于 nuget restore + build。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句