1

我有几个继承 BaseUserControl 的控件。BaseUserControl 继承 System.Web.UI.UserControl。
我想覆盖这样的OnLoad事件:

 public partial class MyControl1 : BaseUserControl
    { 
       protected override void OnLoad(EventArgs e)
       {
          this.Value = myCustomService.GetBoolValue();  
          ///More code here...
          base.OnLoad(e);
       }
    }     

这很好用,唯一的问题是我必须将这段代码复制到 3 个控件中,这是我不喜欢的。(我无权访问 Base 类,因为它被 100 个控件继承。)

所以,我的结果目前看起来像这样:

public partial class MyControl2 : BaseUserControl
        { 
           protected override void OnLoad(EventArgs e)
           {
              this.Value = myCustomService.GetBoolValue();  
              ///More code here...
              base.OnLoad(e);
           }
        }      
 public partial class MyControl3 : BaseUserControl
        { 
           protected override void OnLoad(EventArgs e)
           {
              this.Value = myCustomService.GetBoolValue();  
              ///More code here...
              base.OnLoad(e);
           }
        }   

重构这个的好方法是什么?一种方法是提取

 this.Value = myCustomService.GetBoolValue();  
                  ///More code here...   

到一个单独的方法,但我想知道是否有一种方法可以让我们只指定一次覆盖事件?

4

1 回答 1

2

您可以为这些控件共享功能创建一个额外的基类,并使该类继承自BaseUserControl

// Change YourBaseControl by a meaningful name
public partial class YourBaseControl : BaseUserControl 
{ 
    protected override void OnLoad(EventArgs e)
    {   
        this.Value = myCustomService.GetBoolValue();  
        ///More code here...
        base.OnLoad(e);
    }
}   

public partial class MyControl2 : YourBaseControl
{
   ...
}

public partial class MyControl3 : YourBaseControl
{
   ...
}   
于 2013-05-22T17:09:38.473 回答