[英]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. 我想知道是否有一种方法(以及哪种方法合适)是否可以从LogicalBinaryExpression
检索属性。
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. 在AMethodWhichhandlesThis
方法中,我想要一些可以比较每个属性的东西。 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! 如果我得到了这些,我对其余的代码也没问题……这实际上只是从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 : 当使用表达式执行以下访问者时,其将返回"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
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. 必须修改visitor
以更好地满足您的需求,但是您有一个实现所需内容的起点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.