Passing Function Type in VB.NET

I get a compilation error. The type "ctltype" is not defined using this code.

This is legacy .NET 1.1 code, so I don't know how good it is.

Does anyone know why?

Public Function GetControlText(ByVal ctls As Control, ByVal ctlname As String, ByVal ctltype As Type) As String

        Dim ctl As Control
        Dim res As String


        ctl = ctls.FindControl(ctlname)
        If ctl Is Nothing Then
            Return ""
        End If

        res = CType(ctl, ctltype).Text

        If res Is Nothing Then
            Return ""
        Else
            Return res
        End If

    End Function
+3
source share
1 answer

The second operand for CTypemust be a type name, not a variable having a type Type. In other words, the type must be known at compile time.

In this case, all you need is a property Text- and you can get this with a reflection:

Public Function GetControlText(ByVal ctls As Control, ByVal ctlname As String, _
                               ByVal ctltype As Type) As String

    Dim ctl As Control = ctls.FindControl(ctlname)
    If ctl Is Nothing Then
        Return ""
    End If

    Dim propInfo As PropertyInfo = ctl.GetType().GetProperty("Text")
    If propInfo Is Nothing Then
        Return ""
    End If

    Dim res As String = propInfo.GetValue(propInfo, Nothing)
    If res Is Nothing Then
        Return ""
    End If
    Return res

End Function
+2
source

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


All Articles