我知道这个主题之前已在其他主题中讨论过,但我的问题是关于风格和OOP原则而不是如何。我们的情况是,我们有一个MasterPage内容页面和一个在内容页面中使用的自定义控件。 MasterPage位于MyNamespace命名空间中并公开属性MasterTitle,我们需要从自定义控件(MyControl)设置此属性。我们还添加了<%@ MasterType VirtualPath =“〜/ Site.Master”%>这样我们就可以从内容页面引用Master页面。一位程序员使用以下代码行来设置MasterTitle属性:
((MyNamespace.Site)Page.Master).MasterTitle = "Some Title";
另一位程序员做了一些更复杂的事情。在自定义控件中,他已声明了一个委托:
public delegate void SetMasterTitleDelegate(string masterTitle);
public SetMasterTitleDelegate SetMasterTitle;
然后在内容页面的Page_Init():
MyControl.SetMasterTitle = (masterTitle) => { Master.MasterTitle = masterTitle; };
在MyControl的Page_Load()事件中,设置了MasterTitle属性:
SetMasterTitle("Some Title");
我想知道完成此任务的每种方法的优缺点,因为它与OOP原则有关。
谢谢。
答案 0 :(得分:0)
有很多方法可以实现这一目标。您可以在每个内容页面上创建属性“标题”,并在属性的设置器中设置母版页的标题。另一种方法是在每个内容页面上实现一个接口,该接口可以用作母版页的“合同”。您可以使用设置母版页标题的基础并从内容页面设置它。
但我个人会选择(并使用)你的第一种方法。干净,易于理解。
但OOP明智我认为MS会建议使用站点地图来设置标题和构建菜单/面包库。
答案 1 :(得分:0)
让我们先谈谈这些方法:
方法1:第一种方法非常简单明了,也是最简单的方法。它可以在没有太多开销的情况下使用结论 - 好的方法
方法2:第二种方法似乎要复杂得多,我个人会避免它。在更大的上下文中,您开发的每个自定义控件或子页面都需要这样的方法。
如果在母版页上使用您通常希望在母版页中引用的属性和方法创建和实现接口,我可以想到的唯一其他方法。所以
public interface IMasterContract {
public string Title {get; set;}
}
然后,您可以创建一个继承自System.Web.UI.Page的基类,并在基类中实现相同的接口。在这里,您可以决定是否需要将要设置的标题设置为母版页(如果存在),或者如果不存在则执行您想要的任何其他操作。 所以,
public abstract class AppPage : System.Web.UI.Page, IMasterContract
{
public string IMasterContract.Title {
get
{
if(this.Master!=null && this.Master is IMasterContract)
{
return ((IMasterContract)this.Master).Title;
}
else
{
//return the title from whatever control or variable you've stored it in
}
}
set
{
if(this.Master!=null && this.Master is IMasterContract)
{
((IMasterContract)this.Master).Title = value;
}
else
{
//set the title to whatever control or variable you want to stored it in
}
}
}
}
我所说的方法通常对于可维护性是一个巨大变量的大型应用程序非常有用。 可以集中进行更改,以反映整个应用程序。
对于较小的应用程序,或者如果您尝试尝试的功能仅限于几个位置,我不会去做我已经显示的内容,我宁愿选择方法1。