请考虑以下代码:
Public MustInherit Class BaseClassHandler
Public MustInherit Class MyOwnBaseClass
Inherits TableEntity
Public Property Val As Integer
End Class
Protected Function BuildFilter(PK As String, RK As String) As Expressions.Expression(Of Func(Of MyOwnBaseClass, Boolean))
Return Function(entity) entity.PartitionKey = PK And entity.RowKey = RK
End Function
End Class
Public Class ClassHandler_A
Inherits BaseClassHandler
Public Class MyOwnClass_A
Inherits BaseClassHandler.MyOwnBaseClass
Public Property Val_A As Integer
Public Sub New()
End Sub
End Class
Public Function RetrieveEntity(Table As CloudTable, RowKey As String, PartitionKey As String) As MyOwnClass_A
' Following line gives me a build error
Return Table.CreateQuery(Of MyOwnClass_A).Where(MyBase.BuildFilter(RowKey, PartitionKey)).SingleOrDefault()
End Function
End Class
Public Class ClassHandler_B
Inherits BaseClassHandler
Public Class MyOwnClass_B
Inherits BaseClassHandler.MyOwnBaseClass
Public Property Val_B As Integer
Public Sub New()
End Sub
End Class
Public Function RetrieveEntity(Table As CloudTable, RowKey As String, PartitionKey As String) As MyOwnClass_B
' Following line gives me a build error
Return Table.CreateQuery(Of MyOwnClass_B).Where(MyBase.BuildFilter(RowKey, PartitionKey)).SingleOrDefault()
End Function
End Class
这里我有2个基类,每个类型由其他两个类继承。 我想要完成的是有一个基本方法,可以构建过滤器,然后在派生类中使用。
但是,当然前面报道的代码给了我一个错误,因为过滤器是" build"对于MyOwnBaseClass
而不是任何派生的:
Error 1 Overload resolution failed because no accessible `Where` can be called with these arguments:
[...]
Extension method `Public Function Where(predicate As System.Linq.Expressions.Expression(Of System.Func(Of MyOwnClass_A, Boolean))) As System.Linq.IQueryable(Of MyOwnClass_A)` defined in `System.Linq.Queryable`: Value of type `System.Linq.Expressions.Expression(Of System.Func(Of Test.Form1.BaseClassHandler.MyOwnBaseClass, Boolean))` cannot be converted to `System.Linq.Expressions.Expression(Of System.Func(Of Test.Form1.ClassHandler_A.MyOwnClass_A, Boolean))`
[...]
有没有办法实现我的目的而不必自己构建过滤字符串?
我无法添加C#
标记,因为它会以C#方式重新着色VB发布的代码,但我也会在答案中接受C#。
答案 0 :(得分:0)
好吧,我解决了两次:一次是Expressions.Expression.Lambda
到"转换"我的基地"表达式为继承的实体类的新表达式,第二个,更简单,使用类型约束,如下所示:
Public MustInherit Class BaseClassHandler
Public MustInherit Class MyOwnBaseClass
Inherits TableEntity
Public Property Val As Integer
End Class
Protected Function BuildFilter(Of MyOwnClassT As {MyOwnBaseClass, New})(PK As String, RK As String) As Expressions.Expression(Of Func(Of MyOwnClassT, Boolean))
Dim f As Expressions.Expression(Of Func(Of MyOwnClassT, Boolean)) =
Function(e) e.PartitionKey = PK And e.RowKey = RK
Return f
End Function
End Class
......它就像一个魅力,我喜欢它!
感谢所有针对Expressions.Expression.Lambda
解决方案的StackOverflow社区,你!