base.OnStartup(e) 是做什么的?
What does base.OnStartup(e) do?
我看到很多人像这样在 App.xaml.cs 中使用“base.OnStartup(e)”:
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
MainWindow app = new MainWindow();
app.Show();
}
有必要吗?这样做的目的是什么?
它允许任何基础 class 逻辑到 运行;就像 base
.
的任何其他用法一样
可能严格来说没有必要;但是在覆盖 virtual
方法时调用基础 class 的实现被认为是最佳实践(除非你主动想要抑制基础行为)。
.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);
}
}
我们可以向启动事件添加一个处理程序,而不是覆盖 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();
}
我看到很多人像这样在 App.xaml.cs 中使用“base.OnStartup(e)”:
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
MainWindow app = new MainWindow();
app.Show();
}
有必要吗?这样做的目的是什么?
它允许任何基础 class 逻辑到 运行;就像 base
.
可能严格来说没有必要;但是在覆盖 virtual
方法时调用基础 class 的实现被认为是最佳实践(除非你主动想要抑制基础行为)。
.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);
}
}
我们可以向启动事件添加一个处理程序,而不是覆盖 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();
}