【问题标题】:Extract the lambda from an Expression?从表达式中提取 lambda?
【发布时间】:2010-08-09 07:31:11
【问题描述】:

我要实现这个功能:

Public Function GetFunc(Of TSource, TResult) _
    selector As Expression(Of Func(Of TSource, TResult)) _
        As Func(Of TSource, TResult)
    'Implement here
End Function

更新

我有以下问题,它是函数的一部分:

Dim obj As Object = value
For Each exp In expressions
  If obj Is Nothing Then Return [default]
  Select Case exp.NodeType
    Case ExpressionType.Call
      Dim method = DirectCast(exp, MethodCallExpression)
      Dim info = method.Method          

      If method.Object Is Nothing Then
        Dim args = {obj}.Union(method.Arguments.Skip(1))

        'The following line throws the exception, see details bellow
        obj = info.Invoke(Nothing, args.ToArray)
      Else
        obj = info.Invoke(obj, method.Arguments.ToArray)
      End If

异常详情:

ArgumentException:

Object of type 'System.Linq.Expressions.Expression`1  
[System.Func`3[System.Char,System.Char,System.Char]]'  
cannot be converted to type 
'System.Func`3[System.Char,System.Char,System.Char]'.

【问题讨论】:

    标签: vb.net linq lambda expression-trees


    【解决方案1】:
    Public Function GetFunc(Of TSource, TResult) _
        selector As Expression(Of Func(Of TSource, TResult)) _
            As Func(Of TSource, TResult)
        Return selector.Compile()
    End Function
    

    【讨论】:

    • 好吧,我想我写错了答案,你能帮帮我吗,我更新了我的问题。
    • @Shimmy - 您的异常表明您正在尝试使用ExpressionFunc,就好像它是Func。从FuncExpresson 获取Func 的方法是调用Compile 方法,如this answer所示。
    • 我的问题是我没有找到编译器,在明确转换为 LambdaExpression 之后我找到了它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多