添加OnLoad方法到usercontrol
本文关键字:usercontrol 方法 OnLoad 添加 | 更新日期: 2023-09-27 18:14:47
我有几个继承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个控件,我不喜欢。(我不能访问基类,因为它是由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...
到一个单独的方法,但我想知道是否有一种方法,将允许我们指定重写事件只有一次?
您可以为这些控件共享功能创建一个额外的基类,并使该类继承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
{
...
}