Conditional reference in Visual Studio Community 2017

我怕爱的太早我们不能终老 提交于 2019-12-10 01:45:45

问题


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>


来源:https://stackoverflow.com/questions/46796065/conditional-reference-in-visual-studio-community-2017

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!