MasterPage - 将控件引用为属性的缺点?
在我的 ASP.Net MasterPage 中,有时会有大多数页面需要访问的控件。 现在,我倾向于在 MasterPage 中放置一个属性并引用该控件,而不是使用它来访问控件
((Label)this.Page.Master.FindControl("lblBreadCrumb")).Text = "foo";
,在页面中设置 @MasterType 指令并像这样访问控件:
this.Master.BreadCrumb.Text = "foo";
我发现这种方法更容易使用,但是我从来没有真正见过有人这样做,所以我想知道是否有什么好的理由反对我错过的?
In my ASP.Net MasterPage I sometimes have controls that need to be accessed by most Pages.
Now instead of using this to access the control
((Label)this.Page.Master.FindControl("lblBreadCrumb")).Text = "foo";
I tend to put a Property in the MasterPage with a reference to the Control, set the @MasterType directive in the Page and access the control like this:
this.Master.BreadCrumb.Text = "foo";
I find this approach much easier to use, but I never actually saw someone do it like this so I wonder if there is any good reason against it that I am missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
出于多种原因,使用属性比使用
FindControl
更好,我很高兴您使用这种方法!使用属性的最令人信服的原因是,假设您更改了控件的名称,或者将其全部删除。现在,您遇到了一个编译器错误,该错误更容易被发现。例如,如果您重命名
lblBreadCrumb
并且使用FindControl
,编译器将不会捕获此错误,相反您的应用将在运行时失败。在编译时捕获错误是语言的一大特性。您没有看到许多其他开发人员这样做的原因是,不幸的是,在 Web 表单中几乎找不到良好的 OO 设计。
Using properties is a much better idea than using
FindControl
for several reasons, I'm glad that you're using this approach!The most compelling reason to use properties is lets say you change the name of a control, or remove it all together. Now, you have a compiler error, which is much easier to spot. For example, if you rename
lblBreadCrumb
and you're usingFindControl
, the compiler will not catch this error, and instead your app will fail at run time. Catching errors at compile time is a great feature of a language.The reason why you don't see many other developers doing this is because good OO design is hardly ever found in Web Forms unfortunately.
不,当许多页面访问它时,这是一个很好的方法。
有时,我可能会更抽象一些。例如,我可能不直接直接访问控件,而是在母版页上创建一个属性,如 BreadCrumbText。
No, it's a great approach when many pages will be accessing it.
Sometimes, I may abstract it a little more. For example, instead of simply accessing the control directly, I may just make a property on the master page like BreadCrumbText.