gpt4 book ai didi

c# - 页面继承

转载 作者:行者123 更新时间:2023-12-03 05:45:01 25 4
gpt4 key购买 nike

假设我有一个 Web 项目和一堆不同的 Web 表单,实际上所有不同的类都继承 System.Web.UI.Page

我认为在我的项目中使用的任何页面的 Page_Load 方法中添加一些字段、方法和一些事情会很棒。

即兴地,我想也许创建一个类,比如 MasterPage,它具有我想要的所有字段和方法(具有 protected 级别),并让该类继承 System.Web .UI.Page.

那么我的项目中的每个页面现在都应该继承自 MasterPage,而不是 System.Web.UI.Page

虽然这有效,但也存在一些问题。

  1. 我无法真正轻松地“捕获”仍然从 System.Web.UI.Page 继承的表单。有简单的方法吗?

  2. 由于其设置方式,MasterPage 的 PageLoad 是虚拟的,必须被覆盖,例如:

    protected override void Page_Load(object sender, EventArgs e)
    {
    base.Page_Load(sender, e);
    // rest of stuff for this page...
    }

    有没有更简单的方法可以让父级方法始终首先调用,而无需在每个页面中显式放入基调用?

最佳答案

另一种替代方法是创建从 Page 继承的父类(super class),然后将其自己的事件处理程序添加到 Page 事件中。有时很容易忘记您可以将任意数量的处理程序附加到事件。

namespace MyProject
{
public partial class CustomPage: System.Web.UI.Page
{
public CustomPage()
{
this.Init += new EventHandler(CustomPage_Init);
this.Load += new EventHandler(CustomPage_Load);
this.PreRender += new EventHandler(CustomPage_PreRender);
this.Unload += new EventHandler(CustomPage_Unload);
}

protected void CustomPage_Load(object sender, EventArgs e)
{
//do stuff
}

...
}
}

然后在您的页面中,只需继承并执行您通常执行的操作,两个事件都会触发。

namespace MyProject
{
public partial class NewPage: CustomPage
{
void Page_Load(object sender, EventArgs e)
{
//do more stuff
}
}
}

关于c# - 页面继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11675494/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com