C# 模板使用应用程序启动

根据 .NET 工作负载中的相关更改,C# 的 Windows 窗体模板已更新为支持 global using 指令、文件范围的命名空间和可为 null 的引用类型。 由于典型的 Windows 窗体应用由多个文件(例如 Form1.cs 和 Form1.Designer.cs)中拆分的多个类型组成,因此 Windows 窗体模板中明显缺少顶级语句。 但是,更新后的模板包括应用程序启动代码。 如果你使用的是早期版本的 .NET,这可能会导致不兼容。

引入的版本

.NET 6 RC 1

旧行为

Windows 窗体应用程序入口点如下所示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MyApp
{
    static class Program
    {
        /// <summary>
        ///  The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.SetHighDpiMode(HighDpiMode.SystemAware);
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

新行为

.NET 6+ 应用程序的新应用程序入口点如下所示:

namespace MyApp;

static class Program
{
    /// <summary>
    ///  The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        ApplicationConfiguration.Initialize();
        Application.Run(new Form1());
    }
}

ApplicationConfiguration.Initialize() 是由 Roslyn 编译器(通过源生成器)生成的临时 API。 此方法发出与原始模板相同的调用。 可设置以下 MSBuild 属性来配置此 API 的行为:

如果未显式配置任何属性,则以下代码会在运行时执行:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        // ApplicationConfiguration.Initialize() will emit the following calls:
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.SetHighDpiMode(HighDpiMode.SystemAware);

        Application.Run(new Form1());
    }
}

更改类别

此更改会影响源兼容性

更改原因

应用程序启动功能:

  • 允许 Windows 窗体设计器以首选字体呈现设计图面。
  • 减少模板中的样本代码。

如果使用相同的源来生成面向多个 TFM 的应用程序,则可执行下面其中一项操作:

  • ApplicationConfiguration.Initialize(); 调用替换为原始代码(将失去设计器对 Application.SetDefaultFont API 的支持)。

  • 使用 #if...#endif 指令,例如:

    #if NET6_0_OR_GREATER
            ApplicationConfiguration.Initialize();
    #else
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.SetHighDpiMode(HighDpiMode.SystemAware);
    #endif
    

受影响的 API

不适用