我有一个函数,它根据传入的变量值创建不同类型的表达式。
Protected Function BuildSortPredicate(ByVal tableType As Object, ByRef expr As Expression)
Dim sortExpression As Expression
If tableType Is "Job" Then
sortExpression = Expression.Lambda(Of Func(Of Job, String))(expr)
ElseIf tableType Is "User" Then
sortExpression = Expression.Lambda(Of Func(Of User, Integer))(expr)
...
End If
Return sortExpression
End Function
如何避免冗长的if / else(或case switch)结构? 理想情况下,我正在寻找这样的东西:
Protected Function BuildSortPredicate(ByVal tableType As Object, ByRef exprt As Expression)
Dim sortExpression As Expression
sortExpression = Expression.Lambda(Of Func(Of tableType, String))(expr)
Return sortExpression
End Function
这里的总体目标是将表达式转换为适当的类型,以便我可以在LINQ查询中使用它。
答案 0 :(得分:1)
您想要制作通用功能
Protected Function BuildSortPredicate(Of T)(ByVal expr As Expression) As Expression
Dim sortExpression As Expression
sortExpression = Expression.Lambda(Of Func(Of T, String))(expr)
Return sortExpression
End Function