如何从 .NetStandard class 库引用 net40 框架程序集?

How do I reference net40 framework assembly from .NetStandard class library?

在 project.json 项目系统下,我能够为每个框架指定框架程序集依赖项。 dotnet docs(现已过时)显示以下示例。

{
    "frameworks":{
        "net20":{
            "frameworkAssemblies":{
                "System.Net":""
            }
        },
        "net35":{
            "frameworkAssemblies":{
                "System.Net":""
            }
        },
        "net40":{
            "frameworkAssemblies":{
                "System.Net":""
            }
        },
        "net45":{
            "frameworkAssemblies":{
                "System.Net.Http":"",
                "System.Threading.Tasks":""
            }
        },
        ".NETPortable,Version=v4.5,Profile=Profile259": {
            "buildOptions": {
                "define": [ "PORTABLE" ]
             },
             "frameworkAssemblies":{
                 "mscorlib":"",
                 "System":"",
                 "System.Core":"",
                 "System.Net.Http":""
             }
        },
        "netstandard16":{
            "dependencies":{
                "NETStandard.Library":"1.6.0",
                "System.Net.Http":"4.0.1",
                "System.Threading.Tasks":"4.0.11"
            }
        },
    }
}

如何在 csproj 下为更新的 dotnet sdk v1.1.1 执行此操作?我想为 net40 参考 System.Configuration,但不为 netstandard 1.6 参考。

您可以按照以下步骤操作:

  1. 在 Visual Studio 中右键单击项目并 select 卸载。
  2. 再次右键单击并编辑项目。
  3. 将 "TargetFramework" 值更改为所需的 .Net Framework 版本。例如以下示例将目标框架版本设置为 4.5.2

    <PropertyGroup>
       <TargetFramework>net452</TargetFramework>
    </PropertyGroup>
    
  4. 重新加载项目。

  5. 添加 System.Configuration 程序集的引用。

  6. 再次卸载并编辑项目。

  7. 编辑System.Configuration参考如下。

    <ItemGroup>
      <Reference Include="System.Configuration" Condition="'$(TargetFramework)'=='net452'" />
    </ItemGroup>
    

    可能有我不知道的简单方法,但上述方法应该有效。

谢谢 Pankaj - 我接受了你建议的修改版本。关键只是使用参考元素。

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFrameworks>netstandard1.6;net40</TargetFrameworks>
  </PropertyGroup>

  <ItemGroup Condition="'$(TargetFramework)' == 'netstandard1.6'">
    <PackageReference Include="Microsoft.Extensions.Options" Version="1.1.0" />
    <PackageReference Include="Common.Logging" Version="3.4.0-Beta2" />
    <PackageReference Include="NLog" Version="5.0.0-beta06" />
  </ItemGroup>

  <ItemGroup Condition="'$(TargetFramework)' == 'net40'">
    <PackageReference Include="Common.Logging" Version="3.3.0" />
    <PackageReference Include="NLog" Version="4.1.1" />
    <PackageReference Include="Common.Logging.NLog40" Version="3.3.0" />
    <Reference Include="System.Configuration" />
  </ItemGroup>

  <ItemGroup>
    <Folder Include="Console\" />
  </ItemGroup>

</Project>