您的位置:首页 > 大数据 > 人工智能

WPF使用自定义Main函数

2021-05-15 16:27 1456 查看

一、自定义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_0
56c
006:  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函数,具体如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: