How to perform same operations on both WebControls and HtmlControls
I find myself needing to preform the same actions on both HtmlControls and WebControls. I am a firm believer in DRY and find the fact that there is only the Control class to use if I want to consolidate the functions on both types. The problem that I have with using Control is that there certain properties that both HtmlControl and WebControl expose that Control does not. In the current case, the Attributes property is the problem. Does anyone have any suggestions on how to avoid the duplication of code 开发者_C百科in this type of instance?
Both HtmlControl and WebControl implement the interface IAttributeAccessor (explicitly). Use the IAttributeAccessor.SetAttribute instead. I'm not a vb.net coder, so I leave the task of writing the code to the reader. ;)
In the past I've duplicated code to set the attributes for HtmlControls and WebControls. However, here's another idea:
Private Sub SetAttribute(ByRef ctrl As Control, ByVal key As String, ByVal value As String)
If TypeOf ctrl Is HtmlControl Then
DirectCast(ctrl, HtmlControl).Attributes(key) = value
ElseIf TypeOf ctrl Is WebControl Then
DirectCast(ctrl, WebControl).Attributes(key) = value
End If
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
For Each ctrl In Me.Controls
SetAttribute(ctrl, "class", "classname")
Next
End Sub
I know what you mean. Theoretically, you could do one of the following:
- Use reflection to assign some of those common settings.
- Create a wrapper class that can take either a webcontrol or html control reference, and assign the values. (if control is webcontrol) assign value else if (html is htmlcontrol) assign value, something like that.
- Create another logical class to store the common settings, then another component to copy those settings and apply them to the class.
Ultimately, there isn't any common bridge (no common base class or interface). What kind of assignments are we talking about?
Simon's answer works:
Private Sub SetAttribute(ByRef ctrl As IAttributeAccessor, ByVal key As String, ByVal value As String)
ctrl.SetAttribute(key, value)
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
For Each ctrl In Me.Controls.OfType(Of IAttributeAccessor)()
SetAttribute(ctrl, "class", "classname")
Next
End Sub
精彩评论