[英]Get Properties out of LogicalBinaryExpression ; How?
我想知道是否有一種方法(以及哪種方法合適)是否可以從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中獲取屬性的一部分! 我什至在某個地方讀到我們根本不應該這樣做,但他從未說過……為什么,如果這不是真的,我該怎么做?
對不起我的英語,我通常會說法語。
要從表達式中提取信息,建議使用自定義訪問者。
當使用表達式執行以下訪問者時,其將返回"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
以更好地滿足您的需求,但是您有一個實現所需內容的起點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.