2009-07-29 9 views
3

コンパイルエラーが発生するタイプ "ctltype"はこのコードでは定義されていません。VB.NETの関数に型を渡す

これは.NET 1.1のレガシーコードなので、わかりません。

誰でも知っていますか?

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

は、あなたが1.1を使用していたことを忘れました。答えを削除しました。 – Kirtan

答えて

2

CTypeための第2オペランドがタイプ名でなければならない - ないタイプTypeである変数。つまり、コンパイル時に型を知る必要があります。この場合

、あなたが望むすべてがText財産である - そして、あなたが反射でこれを取得することができます:

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