C# 範本使用應用程式啟動程序

.NET 工作負載的相關變更一樣,C# 的 Windows Forms 範本也已更新為支援 global using 指示詞、檔案範圍命名空間,以及和可為 Null 的參考類型。 因為一般的 Windows Forms 應用程式由橫跨多個檔案上之多種類型分割所組成 (例如 Form1.cs 和 Form1.Designer.cs),所以 Windows Forms 範本很明顯地沒有最上層的陳述式。 但更新後的範本確實包含應用程式啟動程序程式碼。 若是使用舊版的 .NET,這可能會導致不相容。

導入的版本

.NET 6 RC 1

舊的行為

Windows Forms 應用程式進入點類以下列所示:

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 Forms 設計工具以慣用字型呈現設計介面。
  • 減少範本中重複使用的程式碼。

若使用相同的來源建置可以在多個 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

N/A