【问题标题】:Common base class for usercontrols and pages in ASP.NETASP.NET 中用户控件和页面的通用基类
【发布时间】:2009-09-20 11:14:16
【问题描述】:

现在我有一个继承System.Web.UI.Page 的页面基类和另一个继承System.Web.UI.UserControl 的用户控件基类,这些类包含相同的方法。由于 C# 不支持多重继承,我无法将这两个类合并为一个同时继承 Page 和 UserControl 的类。

将功能保留在两个基类中但只在一个地方实现这些方法的最佳方法是什么?

我正在考虑制作一个接口,让两个基类调用包含接口实现的第三个类。有没有更好的方法,这样当我添加一个新方法时,我不必在三个地方都这样做(即使实现只在第三类中)。

【问题讨论】:

  • 你有什么理由不只是创建一个在构造函数中接受 HttpContext 的辅助类吗?这将使您能够执行诸如查看查询字符串和执行 Response.Redirects 之类的操作。
  • 最初的问题是关于 httpContext,它是关于页面基类中的自定义代码(一个常见的用例),它在页面和用户控件之间是 DRY 的。所讨论的方法很可能是特定于业务逻辑的,与 http 上下文无关。

标签: c# asp.net


【解决方案1】:

如果您使用的是 C# 3.0,则可以提供帮助方法作为 System.Web.UI.Control 类的扩展方法,System.Web.UI.PageSystem.Web.UI.UserControl 类都派生自这些类。

public static class ControlExtensions {
    public static void DoSomething(this Control obj) {
       // do something
    }
}

PageUserControl

this.DoSomething();

【讨论】:

    【解决方案2】:

    我也有同样的问题。这是我的解决方案。

    我定义了空接口

    public interface ISecurableWebObject
        {
        }
    

    然后我为上面的接口定义了具有扩展方法的类

    public static class ISecurableWebObjectExtender
        {
            public static bool ExtensionMetotX(this ISecurableWebObject obj)
            {
                return ...;
            }
        }
    

    我在 Page 和 WebUserControl 类中继承了 ISecurableWebObject,所以重复的定义已经消失了。

     public partial class UcExample : System.Web.UI.UserControl, ISecurableWebObject
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                 if(this.ExtensionMetotX() == true)
                 { ... }
            }
        }
    

    【讨论】:

      【解决方案3】:

      嗯...听起来像著名的 Helper 类的用法,基本上是这样的类

      public static class StringHelper
      {
      
          public static string Replace(...)
          {
              ...
          }
      
      }
      

      像这样称呼他们

      string x = StringHelper.Replace(...);
      

      虽然我经常很担心这些 Helper 太多,因为它们确实以某种方式记得使用其中的静态方法进行过程编程。另一方面,您所描述的功能(在一些扩展 UserControl 和 Page 的基类中)通常属于这种类型。

      然后我经常做的是有一个 StringHelper 和一个相应的 StringExtender,它们的内部逻辑调用 Helper 类的静态方法。通过这种方式,您可以使用新的 C# 扩展方法或像往常一样直接通过静态类使用该功能。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-05
        • 1970-01-01
        • 2010-10-28
        • 1970-01-01
        • 1970-01-01
        • 2010-09-20
        • 2010-10-24
        • 1970-01-01
        相关资源
        最近更新 更多