我有几个类继承自基类
Public MustInherit Class BaseClass
Public Property Name as String
End Class
Public MustInherit Class ClassA
Inherits BaseClass
Public Property Something As String
End Class
Public MustInherit Class ClassB
Inherits BaseClass
Public Property SomethingElse As String
End Class
我希望能够使用单个表达式来查询多个对象列表,所有这些都继承自同一个基类
Public Function DoStuff(Expression as System.Linq.Expressions.Expression(Of Func(Of BaseClass, Boolean)))
Dim ListA As New List(Of ClassA) ''Populating this elsewhere
Dim ListB As New List(Of ClassB) ''and this
Dim ResultSetA = ListA.Where(Expression) ''Problems on this line
Dim ResultSetB = ListA.Where(Expression) ''and this
End Function
由于两者都ClassA
继承ClassB
自同一个基类,并且由于 LINQ 查询是针对基类的,因此它应该可以工作。Expression
只能引用基类的属性,这些属性保证在两个派生类上都存在,但我得到以下编译时键入错误:
Value of type 'System.Linq.Expressions.Expression(Of System.Func(Of BaseClass, Boolean))' cannot be converted to 'System.Linq.Expressions.Expression(Of System.Func(Of ClassA, Boolean))'
有什么办法可以添加一个扩大的转换(或类似的东西)来让它工作吗?
还是我需要针对每个派生类多次提供完全相同的查询?