从基类继承Page_Load。正确的面向对象编程

时间:2013-01-13 15:32:39

标签: asp.net inheritance

我在每个网络表单中都重用了我的功能。所以我希望在基类中重用它并让web表单继承基类。我的例子是否使用正确的面向对象实践?  这是一个例子:

using System;
using System.Web;
namespace Template1
{

  public abstract class AllPageBaseClass : System.Web.UI.Page
  {
    public AllPageBaseClass()
    {
      this.Load += new EventHandler(this.Page_Load);
    }

        protected void Page_Load(object sender, EventArgs e)
         {
              if (Session["stuff"] == null)
                  Response.Write("Session Is Empty");
              // More error checking common to all pages here
         }
     }
 }


using System.Lots_Of_Stuff;

//我需要系统;和System.Web;这里??

namespace Template1
{
    public partial class Home : AllPageBaseClass
    {
        protected new void Page_Load(object sender, EventArgs e)
        {
        // All unique Page_load stuff here
        }
        ....
    }
}

1 个答案:

答案 0 :(得分:1)

您无需订阅加载事件。

我的一个项目示例:

public class SecuredPage:System.Web.UI.Page
{
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        if (...) 
        {
            // do something
        }
    }
}

您的内容页面应如下所示:

 public partial class Home : AllPageBaseClass
    {
        protected void Page_Load(object sender, EventArgs e)
        {
          // All unique Page_load stuff here
        }
        ....
    }

您还可以查看new operator的用途。