【发布时间】: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();
}
有需要吗?这样做的目的是什么?
【问题讨论】:
我看到很多人像这样在 App.xaml.cs 中使用“base.OnStartup(e)”:
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
MainWindow app = new MainWindow();
app.Show();
}
有需要吗?这样做的目的是什么?
【问题讨论】:
它允许任何基类逻辑运行;就像base 的任何其他用法一样。
它可能严格没有必要;但是在覆盖 virtual 方法时调用基类的实现被认为是最佳实践(除非您积极地想要抑制基类行为)。
【讨论】:
.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();
}
【讨论】: