我目前有这段代码,我知道它很糟糕,我想尽可能简单地重构它。
if (control as HistoricalLineGraph != null)
{
dock.Title = string.Format(format, dock.ChartName, (control as HistoricalLineGraph).Title);
}
else if (control as HistoricalPieGraph != null)
{
dock.Title = string.Format(format, dock.ChartName, (control as HistoricalPieGraph).Title);
}
HistoricalLineGraph 和 HistoricalPieGraph 都继承自 System.Web.UI.UserControl。
public partial class HistoricalLineGraph : System.Web.UI.UserControl
public partial class HistoricalPieGraph : System.Web.UI.UserControl
它们都有这个 setter/getter :
public string Title
{
get { return Chart1.Titles[0].Text; }
}
由于获取标题依赖于 Chart1 的实例化,因此不可能(轻松)将此 getter 提取到公共(public)基类。我相信我需要使用复合控件来完成这样的事情,但我并不完全肯定,因为我还没有深入探索该解决方案。
是否可以做一些类似于创建一个继承自 System.Web.UI.UserControl 的中间人类,并且该类具有一个 Title 的抽象 getter,然后由我上面的每个类覆盖?如果没有,我还有其他选择吗?
谢谢。
最佳答案
您可以创建一个界面
public interface ITitledControl
{
string Title {get;}
}
并使用
public partial class HistoricalLineGraph : System.Web.UI.UserControl, ITitledControl
public partial class HistoricalPieGraph : System.Web.UI.UserControl, ITitledControl
然后执行此操作
if (control is ITitledControl)
{
dock.Title = string.Format(format, dock.ChartName, (control as ITitledControl ).Title);
}
关于c# - 重构 ASP.NET——两个控件都继承自 Web.UI.UserControl 并具有相同的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5292999/