一、自定義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(指定包含入口點的類型)進行編譯”。此時,我們需要更改應用程序的啟動對象為我們自定義的對象,具體如下:
再次編譯即可完成。
三、程序原先的Main在哪
在以上示例中,我們比較好奇程序原先的Main函數在哪?在代碼完全沒有搜索到,我們使用ildasm.exe查看IL代碼查看,發現App類確實有Main函數。具體如下:
打開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函數,具體如下: