• 无法修改WPF中Application的Main函数


    今日企图重写Application中的Main函数,在App.xaml.cs中加入如下代码:

    public class App : Application

        {

            [STAThread]

            public static void Main()

            {

                WpfApplication.App app = new WpfApplication.App();

                app.Run();

            }

              }

    结果一直编译报错:

    错误         10     类型“WpfApplication.App”已定义了一个名为“Main”的具有相同参数类型的成员         E:\Program\Code\ThesisProject\PFM\WpfApplication\obj\Debug\App.g.cs         59     28     WpfApplication

    发现原来是App.g.cs文件中已经定义了一个Main函数了,所以两个函数冲突了。xx.g.cs是编译器自动生成的一个文件,里面自动帮我们生成了一些模板代码,目的就是为了节省我们编写模板代码的时间。我企图直接把g.cs中的Main函数删掉(我知道这么做很天真),结果不出所料重新编译的时候这个文件又出现了。

    Google之,有人说把partical去掉就行了(试过了,不行),没有找到具体的解决方案。于是我翻开了WPF Programming中的Application生命周期寻找答案。

    结果终于被我找到了,还是要认真的看书才行啊!

    大部分WPF应用程序在创建的时候就会为我们创建Main函数并调用Application实例的run函数,从而启动Application进程。这个Main函数就是g.cs中那个自动生成的Main函数。自动的Main函数如下:

            /// <summary>

            /// Application Entry Point.

            /// </summary>

            [System.STAThreadAttribute()]

            [System.Diagnostics.DebuggerNonUserCodeAttribute()]

            public static void Main() {

                WpfApplication.App app = new WpfApplication.App();

                app.InitializeComponent();

                app.Run();

            }

    这个是由于App.xaml文件的属性中的生成操作(Build Action)所导致的。

    无法修改WPF中Application的Main函数 - imJustice - imJustice 的 学 习 笔 记

     

    你可以将生成操作选择到“无”,这样子你就可以自己写Main函数了!

    且慢!但是为什么微软会自动的替我们生成Main函数呢?它不知道我们如果要改的话很麻烦么?其实它肯定是有原因的,WPFApplication的生命周期可以分为6个阶段:StartUp, Activated, Deactivated, DispatcherUnhandledException, SessionEnding, Exit。这幅图我觉得帮助很好的理解Application 的生命周期。

    无法修改WPF中Application的Main函数 - imJustice - imJustice 的 学 习 笔 记<引用自:http://goo.gl/ZI4dQ>

     

    如图中所示,main函数中Run后就是StartUp了,我们不需要想学校里一样在main函数里加任何东西,可以根据需要在生命周期的不同阶段加入需要的代码,这样会让生命周期各个阶段的分工更加明确。

    如果想要对Application深层次了解,可以去一下网址看看:

    1.       Programming WPF中对于这段的描述:http://goo.gl/mVGxj

    2.       WPF入门教程:理解Application对象:http://goo.gl/Uyaie

    3.       Googlehttp://goo.gl/oqyFw

  • 相关阅读:
    Vue GET xxxx/sockjs-node/info?t=1573626343344 net::ERR_CONNECTION
    NavigationDuplicated Navigating to current location (“/XXX”) is not allowed
    node-sass报错(Node Sass could not find a binding for your current environment)
    DeprecationWarning: collection.ensureIndex is deprecated. Use createIndexes instead
    VSCODE 中.art文件识别为html文件
    gulp4.0构建任务
    gulp报错The following tasks did not complete
    setTimeout()
    格式化日期
    作业1.3
  • 原文地址:https://www.cnblogs.com/imjustice/p/2198115.html
Copyright © 2020-2023  润新知