阅读 138

WPF使用自定义Main函数

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

作者:Dwaynerbing

出处:https://www.cnblogs.com/dongweian/p/14771854.html

服务器评测 http://www.cncsto.com/ 

服务器测评 http://www.cncsto.com/ 


文章分类
后端
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐