Visual Studio for Mac 中具有多个目标框架的项目

重要

根据 Microsoft 的新式生命周期策略,Visual Studio for Mac 计划于 2024 年 8 月 31 日停用。 虽然你可以继续使用 Visual Studio for Mac,但 Mac 上的开发人员还可以使用其他几个选项,例如适用于 VS Code 的新 C# 开发工具包扩展的预览版本。

详细了解支持时间表和替代方案

在 Visual Studio for Mac 中,可将 Xamarin 或 .NET Core 项目配置为在若干 .NET Framework 版本的任一版本和若干系统平台的任一平台上运行。 例如,可以将项目设定为在 .NET Framework 4.6 和 .NET Core 3.1 上运行。

有关目标框架的详细信息,请参阅目标框架

注意

本主题适用于 Visual Studio for Mac。 对于 Windows 上的 Visual Studio,请参阅框架定位概述

面向多个框架

目标框架在项目文件中指定,可通过右键单击项目并选择“工具”>“编辑文件”命令来编辑。 指定单个目标框架时,使用 TargetFramework 元素。 以下控制台应用项目文件演示了如何以 .NET Core 3.0 为目标:

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

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp3.0</TargetFramework>
  </PropertyGroup>

</Project>

将复数形式的 TargetFrameworks 元素与多个目标框架一起使用:

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

  <PropertyGroup>
    <TargetFrameworks>netstandard1.4;net40;net45</TargetFrameworks>
  </PropertyGroup>

详细了解如何面向多个框架

处理多目标项目中的代码

当你在具有多个目标框架的项目中编辑 C# 文件时,可以指定想要用于指导编辑器体验的目标框架(例如,如果使用该框架不支持的 API,则显示警告)。 可以使用编辑器窗口左上角的“目标框架”选择器来更改目标框架。

Using the target framework selector to change the target framework, located at the top of the editor window

有时,需要根据应用程序面向的平台调用不同 API。 为此,可以编写条件代码来编译特定平台的代码:

public class MyClass
{
    static void Main()
    {
#if NET40
        Console.WriteLine("Target framework: .NET Framework 4.0");
#elif NET45  
        Console.WriteLine("Target framework: .NET Framework 4.5");
#else
        Console.WriteLine("Target framework: .NET Standard 1.4");
#endif
    }
}

编写代码时,你将在 IntelliSense 自动完成建议中看到警告,从而知晓应用程序支持的任何目标框架是否缺少特定 API。

A warning message shown in IntelliSense, an API will not work for a specified target framework. Example text: namespace System.Buffers, SharedUtils (netstandard2.0) - Not Available. You can use the navigation bar to switch context.

另请参阅