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

现在我有一个inheritanceSystem.Web.UI.Page页面的基类和inheritanceSystem.Web.UI.Page usercontrols的另一个基类,这些类包含相同的方法。 由于C#不支持多重inheritance,因此我无法将这两个类合并为一个inheritancePage和UserControl的类。

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

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

如果您使用的是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类中inheritance了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(...); 

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

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