WPF使用自定義Main函數

一、自定義Main函數

在WPF中,我們添加一個Program靜態類,添加一個Main靜態方法,需要注意的是該方法需要添加「STAThread」,表示WPF程式需運行在單一執行緒單元下。具體如下:

    static class Program
    {
        [STAThread] 
        static void Main()
        {
            Console.WriteLine("自定義Main函數");
            new MainWindow().ShowDialog();
        }
    }

上述的Main並沒有調用App類,若需要使用App類,那麼自定義Main函數內容如下:

        static void Main()
        {
            Console.WriteLine("自定義Main函數");
            new MainWindow().Show();
            new App().Run();
        }

二、編譯自定義Main函數

此時,編譯程式碼,報錯「程式定義了多個入口點。使用/main(指定包含入口點的類型)進行編譯」。此時,我們需要更改應用程式的啟動對象為我們自定義的對象,具體如下:

image-20210515155049323

再次編譯即可完成。

三、程式原先的Main在哪

在以上示例中,我們比較好奇程式原先的Main函數在哪?在程式碼完全沒有搜索到,我們使用ildasm.exe查看IL程式碼查看,發現App類確實有Main函數。具體如下:

image-20210515161659729

打開Main方法查看程式碼,我們發現該程式碼是程式編譯時生成的,具體如下:

.method public hidebysig static void  Main() cil managed
{
  .entrypoint
  .custom instance void [mscorlib]System.STAThreadAttribute::.ctor() = ( 01 00 00 00 ) 
  .custom instance void [mscorlib]System.Diagnostics.DebuggerNonUserCodeAttribute::.ctor() = ( 01 00 00 00 ) 
  .custom instance void [System]System.CodeDom.Compiler.GeneratedCodeAttribute::.ctor(string,
                                                                                      string) = ( 01 00 16 50 72 65 73 65 6E 74 61 74 69 6F 6E 42   // ...PresentationB
                                                                                                  75 69 6C 64 54 61 73 6B 73 07 34 2E 30 2E 30 2E   // uildTasks.4.0.0.
                                                                                                  30 00 00 )                                        // 0..
  // 程式碼大小       22 (0x16)
  .maxstack  1
  .locals init ([0] class chapter01.App app)
  IL_0000:  nop
  IL_0001:  newobj     instance void chapter01.App::.ctor()
  IL_0006:  stloc.0
  IL_0007:  ldloc.0
  IL_0008:  callvirt   instance void chapter01.App::InitializeComponent()
  IL_000d:  nop
  IL_000e:  ldloc.0
  IL_000f:  callvirt   instance int32 [PresentationFramework]System.Windows.Application::Run()
  IL_0014:  pop
  IL_0015:  ret
} // end of method App::Main

我們打開程式obj/Debug下面的App.g.cs,可以找到Main函數,具體如下:

image-20210515162315699

Tags: