我想知道是否有方法(以及哪种方法)从LogicalBinaryExpression
检索属性,如果可能的话。
我希望有类似的东西:
Dim whereClause as Expression(Of Func(Of Foo, Boolean)) = Function(f as Foo) f.ID = 1
Dim strignifiedWhereClause as string = Me.AMethodWhichhandlesThis(whereClause)
在AMethodWhichhandlesThis
方法中,我希望有一些东西可以让每个属性进行比较。如果我得到这些,我对其余的代码很好......这实际上只是从LogicalBinaryExpression获取属性的一部分!我甚至读到某个地方我们根本不应该这样做,但他从不说......为什么,如果它不是真的我怎么能这样做呢?
对不起我的英语,我通常会说法语。
答案 0 :(得分:1)
要从表达式中提取信息,建议使用自定义访问者。
当您使用表达式执行时,以下访问者将返回"Id = 1"
:
Public Class WhereVisitor
Inherits ExpressionVisitor
Public Shared Function Stringify(expression As Expression) As String
Dim visitor As New WhereVisitor()
visitor.Visit(expression)
Return visitor.Value
End Function
Public Sub New()
Me._value = New StringBuilder()
End Sub
Private _value As StringBuilder
Public ReadOnly Property Value() As String
Get
Return Me._value.ToString()
End Get
End Property
Protected Overrides Function VisitBinary(node As BinaryExpression) As Expression
' node.Left and node.Right is not always of this type
' you have to check the type and maybe use another visitor
' to obtain the information you want
Dim left As MemberExpression = CType(node.Left, MemberExpression)
Dim right As ConstantExpression = CType(node.Right, ConstantExpression)
Me._value.AppendLine(String.Format("{0} = {1}", left.Member.Name, right.Value))
Return MyBase.VisitBinary(node)
End Function
End Class
您可以使用以下方式调用它:
Sub Main()
Dim whereClause As Expression(Of Func(Of Foo, Boolean)) = Function(f As Foo) f.Id = 1
Dim s As String = WhereVisitor.Stringify(whereClause)
Console.WriteLine(s)
End Sub
必须修改visitor
以更好地满足您的需求,但您有一个实现所需内容的起点。