如何为Page和UserControl创建基类?

时间:2011-10-20 18:50:32

标签: c# asp.net inheritance

Page和UserControl的基类:

public class MyWebPage : System.Web.UI.Page { }

public class MyUserControl : System.Web.UI.UserControl { }

他们中的任何一个可能使用的助手:

void SetSessionValue<T>(string key, T value) { Session[key] = value; }

如何实现以下目标?

public class WebObject // can't inherit from both Page and UserControl { 
   protected void SetSessionValue<T>(string key, T value) { 
      Session[key] = value; 
   }
}  

public class MyWebPage : WebObject { }

public class MyUserControl : WebObject { }

更新:我很兴奋第二个希望我能用这种方式解决它,但唉它不能编译。

public class WebObject<T> : T
{
}
public class MyWebPage : WebObject<System.Web.UI.Page>
{
}

4 个答案:

答案 0 :(得分:4)

你做不到。反正不容易。我建议只为页面和用户控件创建一个基类,并在两者中复制公共代码。由于用户控件包含在页面中,因此您只需将Page属性转换为您自己的类型,即可将基本用户控件类中的方法委派给基页类:

// Code in the MyUserControlBase class
public int SomeCommonMethod() {
    return ((MyBasePageType)this.Page).SomeCommonMethod();
}

您还可以通过创建由两个基类实现的接口并使用DI拦截方法和属性访问器调用来使您的生活变得悲惨,然后将其路由到某种实际提供实现的公共代理类。我可能不会去那里:)

答案 1 :(得分:1)

IIRC Page和UserControl都继承自TemplateControl,因此您可以从中继承。

答案 2 :(得分:1)

避免重复的一种方法是拥有一个助手类,通过静态属性进行实例化,并可从UI中的任何位置访问(Page,UserControl或UI层中的任何其他类)。

类似的东西:

public class ApplicationContext
{
    // Private constructor to prevent instantiation except through Current property.
    private ApplicationContext() {}

    public static ApplicationContext Current
    {
        get
        {
            ApplicationContext current = 
                 HttpContext.Current.Items["AppContext"] as ApplicationContext;
            if (current = null)
            {
                current = new ApplicationContext();
                HttpContext.Current.Items["AppContext"] = current;
            }
            return current;
        }
    }

    public void SetSessionValue<T>(string key, T value) 
    { 
        HttpContext.Current.Session[key] = value; 
    }
    ... etc  ... 
}  

单个ApplicationContext实例将在当前请求的生命周期内存在,您可以在UI层代码中的任何位置使用ApplicationContext.Current.SetSessionValue和其他常用成员。

我经常更进一步,比如将SetSessionValue这样的通用方法放在这样的帮助器类中,并且可能在那里有特定于应用程序的属性,例如。

public class ApplicationContext
{
    ... as above ...

    public ShoppingBasket ShoppingBasket
    {
        ShoppingBasket shoppingBasket = 
           HttpContext.Current.Session["Basket"] as ShoppingBasket;
        if (shoppingBasket == null)
        {
            shoppingBasket = ... e.g. retrieve from database
            HttpContext.Current.Session["Basket"] = shoppingBasket;
        }
        return shoppingBasket;
    }
}

通过这种方式,您可以访问UI中任意位置的当前ShoppingBasket实例,而无需知道或关心它是否已在Session中缓存 - 这是仅为您的ApplicationContext类所知的实现细节。

答案 3 :(得分:0)

  • 1)创建一个包含所有变量,所需函数的静态类
  • 2)创建自己的UserControl和Page类,并创建这些类 在Pre_Init和Load overrides中调用静态函数
  • 3)让每个页面都继承你的基类。

这是最简单的方法。

相关问题