C# 将OnLoad方法添加到usercontrol
我有几个继承BaseUserControl的控件。BaseUserControl继承System.Web.UI.UserControl。C# 将OnLoad方法添加到usercontrol,c#,asp.net,inheritance,C#,Asp.net,Inheritance,我有几个继承BaseUserControl的控件。BaseUserControl继承System.Web.UI.UserControl。 我想覆盖OnLoad事件,如下所示: public partial class MyControl1 : BaseUserControl { protected override void OnLoad(EventArgs e) { this.Value = myCustomService.GetBo
我想覆盖
OnLoad
事件,如下所示:
public partial class MyControl1 : BaseUserControl
{
protected override void OnLoad(EventArgs e)
{
this.Value = myCustomService.GetBoolValue();
///More code here...
base.OnLoad(e);
}
}
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);
}
}
这非常有效,唯一的问题是我必须跨3个控件复制这段代码,这是我不喜欢的。(我没有访问基类的权限,因为它是由100个控件继承的。)
因此,我的结果目前如下所示:
public partial class MyControl1 : BaseUserControl
{
protected override void OnLoad(EventArgs e)
{
this.Value = myCustomService.GetBoolValue();
///More code here...
base.OnLoad(e);
}
}
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...
对于一个单独的方法,但我想知道是否有一种方法允许我们只指定一次覆盖事件?您可以为那些共享功能的控件创建一个额外的基类,并使该类继承自
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
{
...
}
为什么不创建中间类SetBoolValueOnLoadContorl:BaseControl,然后使用MyControl1:SetBoolValueOnLoadContorl,MyControl2:SetBoolValueOnLoadContorl?