2009-07-29 16 views
3

Ich bekomme einen Kompilierfehler Typ "Ctltype" ist nicht mit diesem Code definiert.Übergabe von Typ an eine Funktion in VB.NET

Dies ist .NET 1.1 Legacy-Code, so nicht gut, ich weiß.

Wer weiß warum?

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

vergessen, dass Sie 1.1 verwendet haben. Habe die Antwort gelöscht. – Kirtan

Antwort

2

Der zweite Operand für CType hat ein Typ Name sein - nicht eine Variable, die von Type Typ ist. Mit anderen Worten, der Typ muss zur Kompilierzeit bekannt sein.

In diesem Fall alles, was Sie wollen, ist die Text Eigenschaft - und Sie können dies mit Reflexion erhalten:

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 
Verwandte Themen