Conditional reference in Visual Studio Community 2

2020-08-11 11:08发布

问题:

I am creating a multi-platform application. I have a multi-targeted shared library (targeting .netstandard 2.0 and .net 4.5)...See project file:

  <PropertyGroup>
    <TargetFrameworks>netstandard2.0;net45</TargetFrameworks>
  </PropertyGroup>

When I build the project in visual studio 2017 on windows, I get two directories in the output (netstandard2.0, net45) and the corresponding dlls. The build is a success.

When I build the exact same project (same code) in visual studio 2017 on a mac, I get errors of this nature:

The type 'OptionAttribute' exists in both 'CommandLine.DotNetStandard, Version=1.0.30' and 'CommandLine, Version=1.9.71.2'

I conditionally referenced a command line parser library in the following way:

  <!-- CommandLineParser library -->
  <ItemGroup Condition="'$(TargetFramework)' == 'netstandard2.0'">
    <PackageReference Include="CommandLine.DotNetStandard">
      <Version>1.0.3</Version>
    </PackageReference>
  </ItemGroup>

  <ItemGroup Condition="'$(TargetFramework)' == 'net45'">
    <PackageReference Include="CommandLineParser">
      <Version>1.9.71</Version>
    </PackageReference>
  </ItemGroup>

This works great for windows, but on the mac it appears it is not observing the condition. Is this a known bug for visual studio on mac? Am I doing something wrong?

回答1:

Visual Studio ignores the condition in these cases. Use a Choose/When instead, that should be fully supported: https://msdn.microsoft.com/en-us/library/ms164282.aspx

<Choose> 
  <When Condition=" '$(TargetFramework)' == 'netstandard2.0' ">
    <ItemGroup>
      <PackageReference Include="CommandLine.DotNetStandard">
        <Version>1.0.3</Version>
      </PackageReference>
    </ItemGroup>
  </When>
  <When Condition=" '$(TargetFramework)' == 'net45' ">
    <ItemGroup> 
      <PackageReference Include="CommandLineParser">
        <Version>1.9.71</Version>
      </PackageReference>
    </ItemGroup>
  </When>
</Choose>


回答2:

If MsBuild is taking into account only your first <Choose/> or condition then you'd want to do this:

 <Choose>
    <When Condition="'$(Configuration)'=='Debug'">
      <ItemGroup>
        <ProjectReference Include="..\path\to_your_project.csproj" />
      </ItemGroup>
    </When>
    <Otherwise>
      <ItemGroup>
        <PackageReference Include="Package-Name" Version="1.0.0"/>
      </ItemGroup>
    </Otherwise>
  </Choose>