簡體   English   中英

.NET:通過項目配置實現不同的目標框架

[英].NET: Different target frameworks via project configuration

我想通過 Visual Studio 2015 中的配置獲得兩個不同的 .net 框架目標。雖然作為參考,您可以編輯 CSPROJ 文件並添加條件,但這似乎不適用於文件第一個PropertyGroup中的TargetFrameworkVersion 我的印象是該元素中的任何Condition都會導致 VS 完全忽略該元素並回退到“v4.0”的默認值。

有什么辦法可以為不同的配置獲得不同的目標框架版本嗎?

這是我在 CSPROJ 文件中嘗試的:

<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    ...
    <!-- this is what VS2015 would put into the file:
    <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
    -->
    <!-- this is what does not work: -->
    <TargetFrameworkVersion Condition="'$(Configuration)' == 'OLD_Debug' OR '$(Configuration)' == 'OLD_Release'">v3.5</TargetFrameworkVersion>
    <TargetFrameworkVersion Condition="'$(Configuration)' == 'NEW_Debug' OR '$(Configuration)' == 'NEW_Release'">v4.0</TargetFrameworkVersion>
    ...
  </PropertyGroup>
  ...
</Project>

具有裝配參考條件的類似方法可以正常工作。

編輯我發現了一個類似的 Stackoverflow 問題: Targetting multiple .net framework versions by using different project configuration並嘗試了未接受的答案中建議的方法從第一個PropertyGroup塊中刪除TargetFrameworkVersion ,並編輯后面的<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'OLD_Debug|AnyCPU' ">包含它的塊,但無論我使用哪種配置,我的程序集仍然為框架 3.5 編譯。 至少如果我使用[System.Reflection.Assembly]::LoadFrom("C:\\PATH\\MyAssembly.dll").ImageRuntimeVersion從 Powershell 查看程序集,我總是得到版本 2,而不是 4。

這個對類似問題的回答中找到的方法有效:保持第一個PropertyGroup沒有配置特定設置,從中刪除TargetFrameworkVersion元素。 並將TargetFrameworkVersion設置添加到文件中的配置特定PropertyGroup中,只需將它們加倍即可進行調試/發布:

<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    ...
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'OLD_Debug|AnyCPU' ">
    ...
    <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'OLD_Release|AnyCPU' ">
    ...
    <TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'NEW_Debug|AnyCPU' ">
    ...
    <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
  </PropertyGroup>
  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'NEW_Release|AnyCPU' ">
    ...
    <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
  </PropertyGroup>
  ...
</Project>

我驗證了如下:

  1. 我的程序集引用了 3.5 框架的 mscorlib 程序集的 2.0.0.0 版( OLD_...配置),以及 4.0 框架的 mscorlib 的 4.0.0.0 版( NEW_...配置)。
  2. 使用ILSpy ,我發現我的程序集的 3.5 版本沒有目標框架的屬性,因為這是從版本 4 開始引入的,但版本 4 框架作為程序集的一個屬性出現:

     [assembly: TargetFramework(".NETFramework,Version=v4.0", FrameworkDisplayName = ".NET Framework 4")]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM