简体   繁体   中英

Visual Studio - Change target framework when multitargeting

IS there a way to change what framework a project (that has multiple target frameworks) is compiled in without updating the csproj?

I'm writing a NuGet package that supports both .NET 4.8 and .NET 6. (I can't use .NET Standard 2.0.)

I have files that I want to be compiled only when targeting .NET 4.8 and others that should only be compiled when targeting .NET 6.0. I know there's a couple ways to achieve this, but I am trying to structure my files such that the directory /AspNetCore contains all of my .NET 6 files and /NetFramework contains all my .NET 4.8 files.

With that, in my csproj, I can do:

<ItemGroup Condition="'$(TargetFramework)' == 'net6.0'">
  <Compile Remove="NetFramework\**" />
  <EmbeddedResource Remove="NetFramework\**" />
  <None Remove="NetFramework\**" />
</ItemGroup>

<ItemGroup Condition="'$(TargetFramework)' == 'net48'">
    <Compile Remove="AspNetCore\**" />
    <EmbeddedResource Remove="AspNetCore\**" />
    <None Remove="AspNetCore\**" />
</ItemGroup>

But then the /AspNetCore folder is hidden because the IDE is choosing NET48 as the target framework. This is fine when I'm working on the NET48 code, but not ideal when I'm working on the NET6.0 code.

在此处输入图像描述

If I were using #if NETFRAMEWORK #elif NET6_0 #endif syntax in each file, then I could select the target framework from the project dropdown, but I want to avoid having compile-time logic in my files. I could also keep going back to my csproj and updating the tag, but I don't want to do that either in case I accidentally forget to change it back.

Is there a good to change the target framework in the IDE when targeting multiple frameworks like this?

Create a Directory.Build.targets file in your solution folder and copy the contents below:

<Project>

  <PropertyGroup>
    <BuildDependsOn>
      RemoveNet48Files;
      RemoveNet60Files;
      $(BuildDependsOn)
    </BuildDependsOn>
  </PropertyGroup>

  <Target Name="RemoveNet48Files" Condition="'$(TargetFramework)' != 'net48'">
    <ItemGroup>
      <Compile Remove="NetFramework\**" />
      <EmbeddedResource Remove="NetFramework\**" />
      <None Remove="NetFramework\**" />
    </ItemGroup>
  </Target>

  <Target Name="RemoveNet60Files" Condition="'$(TargetFramework)' != 'net6.0'">
    <ItemGroup>
      <Compile Remove="AspNetCore\**" />
      <EmbeddedResource Remove="AspNetCore\**" />
      <None Remove="AspNetCore\**" />
    </ItemGroup>
  </Target>

</Project>

This way the files will be removed from the item group only before build.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM