【问题标题】:What does base.OnStartup(e) do?base.OnStartup(e) 有什么作用?
【发布时间】:2018-11-29 18:20:25
【问题描述】:

我看到很多人像这样在 App.xaml.cs 中使用“base.OnStartup(e)”:

protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);

    MainWindow app = new MainWindow();
    app.Show();
}

有需要吗?这样做的目的是什么?

【问题讨论】:

标签: c# wpf app.xaml


【解决方案1】:

它允许任何基类逻辑运行;就像base 的任何其他用法一样。

它可能严格没有必要;但是在覆盖 virtual 方法时调用基类的实现被认为是最佳实践(除非您积极地想要抑制基类行为)。

【讨论】:

    【解决方案2】:

    .NET Framework 代码可以在https://referencesource.microsoft.com找到

    Application.OnStartup() 不包含太多功能:

    /// <summary>
    ///     OnStartup is called to raise the Startup event. The developer will typically override this method
    ///     if they want to take action at startup time ( or they may choose to attach an event).
    ///     This method will be called once when the application begins, once that application's Run() method
    ///     has been called.
    /// </summary>
    /// <param name="e">The event args that will be passed to the Startup event</param>
    protected virtual void OnStartup(StartupEventArgs e)
    {
        // Verifies that the calling thread has access to this object.
        VerifyAccess();
    
        StartupEventHandler handler = (StartupEventHandler)Events[EVENT_STARTUP];
        if (handler != null)
        {
            handler(this, e);
        }
    }
    

    我们可以向 Startup 事件添加一个处理程序,而不是覆盖 OnStartup():

    <Application x:Class="WpfApp.App"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 Startup="LaunchWpfApp"> 
    
    private void LaunchWpfApp(object sender, StartupEventArgs e)
    {
        MaiWindow app = new MainWindow();
        app.Show();
    }
    

    【讨论】:

    • 这确实不能回答问题。我得到了 Application.OnStartup() 的作用。我也明白我可以像我的代码中显示的那样覆盖它。我的问题是针对为什么人们使用“base.OnStartup(e);”在“Application.OnStartup()”中
    猜你喜欢
    • 2013-01-01
    • 2018-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多