问题描述
谁能告诉我是否应该在我的项目中尽可能多地使用用户控件?Ff 那么为什么,如果不是,为什么不呢?
Can some one please tell me if I should use user controls in my project as much as I can? Ff so why and if not why not?
推荐答案
这是一个有趣的问题;但是这样想.
It's an interesting question; but think of it this way.
您刚刚编写了一个表格,列出了所有用户.您在网站的列出用户"页面上显示此内容.
You've just written a table, listing all of your users. You show this on the List Users page of your website.
在查找用户"页面上,您可能希望能够显示用户列表.您是否像以前一样重写相同的 HTML、代码、javascript、CSS?或者您是否重复使用该控件,这次添加了按用户名或其他属性进行过滤的功能?
On the "Find User" page, you might want to be able to show a list of users. Do you rewrite the same HTML, code, javascript, CSS as before? Or do you reuse the control, this time adding the ability to filter by a user name or other attributes?
本质上,用户控件用于打包您网站的可重复使用部分.无需在各处重复相同的代码,您可以将其打包到用户控件中,然后只需添加适当的标记即可将其添加到您想要的任何页面.
Essentially, user controls are there to package up reusable bits of your website. Rather than repeating the same code everywhere, you can package it up in a user control, and simply add it to any page you want just by adding the appropriate tag.
此外,您刚刚在项目中创建了一个控件来负责处理某些功能 - 它的所有逻辑都在一个位置并与其他代码分开.这也是一个重要的概念,因为它可以防止所有代码混在一起.在用户示例中,您可以通过界面与用户列表进行交互,而不是将其与可能执行不同操作的其他代码混合.这称为 SRP,可能是一件好事.
Also, you have just made ONE control in your project responsible for dealing with some functionality - all of the logic for it is in one place and separated from other code. This is an important concept too, as it stops all of your code being jumbled together. In the users example, you can interact with a list of users through an interface, rather than mixing it with other code that might do different things. This is called SRP and can be a good thing.
作为一个实际示例,我们有一个显示我们产品列表的控件.我们可以在 Find 屏幕、Admin 屏幕、Products Like this"屏幕和Products you have selected"屏幕上重复使用相同的控件.这段代码包含很多逻辑,都在一个地方,所以维护方便,复用也很简单.
As a practical example, we have a control that shows a list of our products. We can reuse the same control on the Find screen, the Admin screen, the "Products Like this" screen, and on the "Products you have chosen" screen. This code contains a lot of logic that is all in one place so it can be maintained easily, and it can be reused very simply too.
用户控件可能是一件非常好的事情.因此,当您觉得可以打包一组现有控件、HTML 等时,您应该使用它们.这使它们可重用,并且更易于维护.
User Controls can be a very good thing. So you should use them when you feel like you can package up a group of existing controls, HTML etc. It makes them reusable, and much easier to maintain.
还有自定义控件的概念 - 这些通常是现有控件的重新实现 - 例如,您可能有一个 ExtendedTextBox,它可以在有人键入文本时验证文本.
There is also the concept of custom controls - these are usually reimplementations of existing controls - you might have an ExtendedTextBox, for example, that validates the text as someone types it.
您可以在此处阅读有关这两种控件的更多信息
这篇关于asp.net中usercontrol的优缺点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!