开发者

VB.NET generic function to return a control

I have created a couple of simple functions in VB.NET that simply return a control of a certain type that I already know, such as HtmlInputHidden, Label, etc. That means that each of the functions is created only for that special purpose.

What I'd like to do is combine all those functions into one function using generics. The common things shared by each of the functions is a control Id and a control type.

What I have got so far is:

   Public Function GetControl(Of T)(ByVal ctrlId As String) As T
        Dim ctrl As Control = Me.FindControl(ctrlId)

        If (Not ctrl Is Nothing) Then
            GetControl = CType(ctrl, T)
        Else
            GetControl = Nothing
        End If
    End Function

But the line " GetControl = CType(ctrl, T)" is giving me a compile error:

   Value of type 'System.Web.UI.Control' cannot be converted to 'T'

This is in .NET Framework 2.0.

开发者_开发百科Any insight is highly appreciated.

John


If you change your function to this, it will work.

Public Function GetControl(Of T)(ByVal ctrlId As String) As T
    Dim ctrl As Object = Me.FindControl(ctrlId)

    If (Not ctrl Is Nothing) Then
        return  CType(ctrl, T)
    Else
        return  Nothing
    End If
End Function

This is due to the fact that the type needs to be in a way that it can convert, as if you convert to a control, it would be upcasting to the concrete type.

Now, be sure to keep in mind that you could throw exceptions here if your send the id of the wrong type, etc.


Here is a more concise way of adding it - you can't call it using a type that does not inherit from Control:

Public Function GetControl(Of T As Control)(ByVal ctrlId As String) As T
    Dim ctrl As Control = Me.FindControl(ctrlId)

    If (Not ctrl Is Nothing) Then
        GetControl = CType(ctrl, T)
    Else
        GetControl = Nothing
    End If
End Function
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜