繁体   English   中英

ASP.NET中用户控件和页面的公共基类

[英]Common base class for usercontrols and pages in ASP.NET

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

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

我正在考虑创建一个接口,让两个基类调用包含接口实现的第三个类。 有没有更好的方法,所以当我添加一个新方法时,我不必在三个地方做到这一点(即使实现仅在第三类)。

如果您使用的是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();

我有完全相同的问题。 这是我的解决方案。

我定义了空接口

public interface ISecurableWebObject
    {
    }

然后我定义了具有上述接口的extesion方法的类

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

我在Page和WebUserControl类中继承了ISecurableWebObject,因此dublicate定义已经消失了。

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

嗯......听起来像是着名的Helper类的用法,基本上类似于

public static class StringHelper
{

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

}

并称他们为

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

虽然我经常非常关心拥有太多的这些助手,因为他们真的不记得用其中的静态方法进行程序化编程。 另一方面,您描述的功能(在一些扩展UserControl和Page的基类中)通常属于这种类型。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM