我正在尝试创建一个通用类,它将为任何强类型数据表提供一些附加功能。其中许多功能使用一种功能,允许用户使用类型的强类型字段指定在强类型数据表中查找行的条件。当我尝试将Func(Of T,Boolean)传入一个期望Func(Of datarow,Boolean)的Where子句时,就会出现问题。我的泛型类确保T继承自datarow,所以我不明白为什么我会得到一个无效的强制转换异常。
Module Module1
Sub Main()
Dim strongTable As New StrongTypedTable
Dim explorer As New DependencyExplorer(Of StrongTypedRow)(strongTable)
Dim row As StrongTypedRow = explorer.FindRows(Function(r) r.MyColumn = 1)
End Sub
End Module
Public Class StrongTypedTable
Inherits DataTable
Public Sub New()
Columns.Add(New DataColumn("MyColumn", GetType(Integer)))
End Sub
Protected Overrides Function GetRowType() As Type
Return GetType(StrongTypedRow)
End Function
Protected Overrides Function NewRowFromBuilder(builder As DataRowBuilder) As DataRow
Return New StrongTypedRow(builder)
End Function
End Class
Public Class StrongTypedRow
Inherits DataRow
Friend Sub New(builder As DataRowBuilder)
MyBase.New(builder)
End Sub
Public Property MyColumn() As String = MyBase.Item("MyColumn")
End Class
Public Class DependencyExplorer(Of rowType As DataRow)
Private _table As DataTable
Public Function FindRows(ByVal whereClause As Func(Of rowType, Boolean)) As IEnumerable(Of rowType)
Return _table.AsEnumerable.Where(whereClause)
End Function
Public Sub New(ByVal table As DataTable)
_table = table
End Sub
End Class