简体   繁体   中英

Get Properties out of LogicalBinaryExpression ; How?

I would like to know if there is a way (and which is proper) to retrieves properties from a LogicalBinaryExpression , if it's possible.

I would like to have something like :

Dim whereClause as Expression(Of Func(Of Foo, Boolean)) = Function(f as Foo) f.ID = 1

Dim strignifiedWhereClause as string = Me.AMethodWhichhandlesThis(whereClause)

In the AMethodWhichhandlesThis methods, I would like to have something which get each properties to compare. If I get these, I'm fine with the rest of the code... this is really only the part of getting properties out of LogicalBinaryExpression! I even read somewhere that we should not do that at all but he never says... why, and how can I do this if it's not real?

Sorry for my english, I usually talk french.

To extract information from an expression it is recommend to use a custom visitor.

The following visitor will return "Id = 1" when you execute it with your expression :

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

You can call it using :

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

The visitor has to be modified to better fit your needs but you have a start point to implement what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM