English 中文(简体)
返回控件的VB.NET泛型函数
原标题:VB.NET generic function to return a control

我在VB.NET中创建了几个简单的函数,这些函数只返回我已经知道的某个类型的控件,例如HtmlInputHidden、Label等。这意味着每个函数都只是为了这个特殊目的而创建的。

我想做的是使用泛型将所有这些函数组合成一个函数。每个函数共享的共同点是控件Id和控件类型。

到目前为止,我得到的是:

   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

但是“GetControl=CType(ctrl,T)”这一行给了我一个编译错误:

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

这是在.NET Framework 2.0中。

任何见解都将不胜感激。

约翰

最佳回答

如果你把你的功能改成这个,它就会起作用。

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

这是因为类型需要以一种可以转换的方式,就好像转换为控件一样,它将向上转换为具体类型。

现在,请务必记住,如果您发送了错误类型的id等,则可能会在此处引发异常。

问题回答

以下是添加它的更简洁的方法-不能使用非继承自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




相关问题
Is Shared ReadOnly lazyloaded?

I was wondering when I write Shared ReadOnly Variable As DataType = New DataType() Or alternatively Shared ReadOnly Variable As New DataType() Is it lazy loaded or as the instance initializes? ...

Entertaining a baby with VB.NET

I would like to write a little application in VB.NET that will detect a baby s cry. How would I get started with such an application?

Choose Enter Rather than Pressing Ok button

I have many fields in the page and the last field is a dropdown with list of values. When I select an item in a dropdown and press Enter, it doesn t do the "Ok". Instead I have to manually click on Ok ...

ALT Key Shortcuts Hidden

I am using VS2008 and creating forms. By default, the underscore of the character in a textbox when using an ampersand is not shown when I run the application. ex. "&Goto Here" is not ...

Set Select command in code

On button Click I want to Set the Select command of a Gridview. I do this and then databind the grid but it doesn t work. What am i doing wrong? protected void bttnView_Click(object sender, ...

Hover tooltip on specific words in rich text box?

I m trying to create something like a tooltip suddenly hoovering over the mouse pointer when specific words in the richt text box is hovered over. How can this be done?

热门标签