How to perform the same operations for both WebControls and HtmlControls

I need to follow the same steps as for HtmlControls and WebControls. I strongly believe in DRY and find that there is only the Control class if I want to consolidate functions on both types. The problem I am encountering with using a control is that there are certain properties that HtmlControl and WebControl detect that Control does not support. In the current case, the Attributes property is a problem. Does anyone have any suggestions on how to avoid code duplication in this type of instance?

+3
source share
4 answers

In the past, I have duplicated code for setting attributes for HtmlControls and WebControls. However, here is 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        
+2
source

Both HtmlControl and WebControl implement the IAttributeAccessor interface (explicitly). Use IAttributeAccessor.SetAttribute instead . I am not a vb.net encoder, so I leave the task of writing code to the reader .;)

+3
source

, . :

  • , .
  • -, webcontrol html . ( webcontrol) else if (html is htmlcontrol) , - .
  • Create another logical class to hold the general parameters, then another component that will copy these parameters and apply them to the class.

Ultimately, there is no common bridge (no common base class or interface). What appointments are we talking about?

+2
source

Simon replies:

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
0
source

Source: https://habr.com/ru/post/1729082/


All Articles