[英]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.