PackageReference 条件被忽略

Bob*_*sky 6 msbuild csproj visual-studio docfx

在我的 VS 2017 项目中,我引用了 docfx.console 包,我希望它仅在满足特定条件时使用。但是该包被用于所有构建。

这是我项目的一部分。我希望在配置为 Installer/AnyCPU 并且 VS 正在构建 net40 风格时使用 docfx.console。

<?xml version="1.0" encoding="utf-8"?>
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFrameworks>net40;netstandard1.3;netstandard2.0</TargetFrameworks>
    <!-- ... -->
    <Configurations>Debug;Release;Installer</Configurations>
  </PropertyGroup>

  <ItemGroup Condition=" '$(TargetFramework)'=='net40' ">
    <!-- ... -->
    <PackageReference Include="docfx.console" Version="2.30.0" Condition="'$(Configuration)|$(Platform)'=='Installer|AnyCPU'" />
  </ItemGroup>

    <!-- ... -->
</Project>
Run Code Online (Sandbox Code Playgroud)

有没有办法在仅针对 net40 的安装程序构建中使用 docfx.console?

Luk*_*oen 9

总而言之,即使条件为“false”,包也会被导入。

<Project Sdk="Microsoft.NET.Sdk">    
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFrameworks>netcoreapp3.0;netcoreapp2.2;net472</TargetFrameworks>
    <Platforms>x64;x86</Platforms>
  </PropertyGroup>
  <ItemGroup Condition="false">
      <PackageReference Include="MyPackage" Version="1.0.0" />
  </ItemGroup>
</Project>
Run Code Online (Sandbox Code Playgroud)

我们发现我们可以通过将 packagereference 放在不同的文件中来解决这个问题,并使文件的导入有条件。

单独的文件:packagerefs.targets

<Project Sdk="Microsoft.NET.Sdk">    
  <ItemGroup>
      <PackageReference Include="MyPackage" Version="1.0.0" />
  </ItemGroup>
</Project>
Run Code Online (Sandbox Code Playgroud)

项目文件:

<Project Sdk="Microsoft.NET.Sdk">    
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFrameworks>netcoreapp3.0;netcoreapp2.2;net472</TargetFrameworks>
    <Platforms>x64;x86</Platforms>
  </PropertyGroup>
  <Import Project="packagerefs.targets" Condition="false" />
</Project>
Run Code Online (Sandbox Code Playgroud)


Nar*_*tty 9

即使我正在寻找基于条件的引用 nuget 包(仅当在 DefineConstants 中设置预期常量时才加载)。尽管@Luke Schoen 解决方案对我有用,但我可以在没有外部目标文件的情况下使其工作。

解决方案是使用“选择”>“何时”包含您的 PackageReference

确保在你的 PropertyGroup 之后有这个块,它有 DefineConstants。

<Choose>
<When Condition="$(DefineConstants.Contains('My_CONST'))">
  <ItemGroup>
  <PackageReference Include="MyPackage">
    <Version>1.0.6</Version>
  </PackageReference>
  </ItemGroup>
</When>  </Choose>
Run Code Online (Sandbox Code Playgroud)