【问题标题】:ASP.NET Session InheritenceASP.NET 会话继承
【发布时间】:2009-10-21 05:06:58
【问题描述】:

我的页面和控件继承自两个类。这两个类获得相同的基本信息集,但就目前而言,代码被实现了两次。有没有办法从一个基类继承?

public partial class SessionPage : System.Web.UI.Page
{
    protected override void OnInit(EventArgs e)
    {
        // Loads the session information from the database
        // stores in member vars for the page to use
    }
}

public partial class SessionControl : System.Web.UI.UserControl
{
    protected override void OnInit(EventArgs e)
    {
        // Loads the session information from the database
        // stores in member vars for the user control to use
    }
}

【问题讨论】:

    标签: c# asp.net inheritance


    【解决方案1】:

    看看这个stackoverflow post,它以某种方式解决了您的问题。

    你的

    // Loads the session information from the database
    // stores in member vars for the page to use
    

    可以作为扩展方法实现,允许您重用页面和用户控件内部的逻辑。

    【讨论】:

      【解决方案2】:

      C# 不允许多重继承,您需要从 Page 或 UserControl 继承。所以,不,没有办法从同一个基类继承。

      您应该适当地将加载和初始化逻辑放在它自己的类中;那么你可以在 OnInit 方法中实例化这个类的一个实例。这样可以避免重复代码。

      【讨论】:

        【解决方案3】:

        您可以将逻辑放在一个类中,然后让 Page 和 UserControl 自定义类扩展一个通用接口。

        您仍然需要像您一样对 Page 和 UserControl 进行子类化,但至少不会重复逻辑,只有重载的方法和对公共逻辑类的调用。不过,出于代码共享的原因,这仍然是一个改进。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-11-11
          • 2011-02-14
          • 1970-01-01
          • 2011-02-19
          • 1970-01-01
          相关资源
          最近更新 更多