简体   繁体   English

在泛型方法中强制转换为泛型

[英]Cast to Generic Type in Generic Method

I'm trying to write a method to return a list of all of a particular type of control: 我正在尝试编写一种方法来返回所有特定类型控件的列表:

So I have something like the following method: 所以我有类似下面的方法:

Private Function GetAllChildControls(Of T)(ByVal grid As DataGridItemCollection) 
                                           As List(Of T)
    Dim childControls As New List(Of T)
    For Each item As DataGridItem In grid 
        For Each tableCell As TableCell In item.Cells
            If tableCell.HasControls Then
                For Each tableCellControl As Control In tableCell.Controls
                    If tableCellControl.GetType Is GetType(T) Then

                        childControls.Add(DirectCast(tableCellControl, T))

                    End If
                Next
            End If
        Next
    Next
    Return childControls
End Function

But this fails on the following code: 但这在以下代码上失败:

childControls.Add(DirectCast(tableCellControl, T))

I get the message: 我收到消息:

Cannot cast expression of type System.Web.UI.Control to type T . 无法将类型System.Web.UI.Control表达式转换为类型T

How can I return a type specific list? 如何返回特定类型的列表?

Generics can be anything , so the compiler has no way of knowing that you only intend to call this method on types that inherit from System.Web.UI.Control . 泛型可以是任何东西 ,因此编译器无法知道您仅打算对从System.Web.UI.Control继承的类型调用此方法。 You could, in fact, call the function with Type Integer , in which case the conversion will fail. 实际上,您可以使用Type Integer调用该函数,在这种情况下,转换将失败。

What you need to do is convince the compiler that you will only pass in certain types by using Generic Constraints . 您需要做的是使编译器确信,您将仅使用Generic Constraints传递某些类型。 Then you can only allow applicable types to call into the method. 然后,您只能允许适用的类型调用该方法。

All you need to do is modify your signature like this: 您需要做的就是像这样修改您的签名:

Private Function GetAllChildControlsInDataGrid(Of T As Control)(
                      ByVal grid As DataGridItemCollection) As List(Of T)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM