从表达式中提取lambda?

时间:2010-08-09 07:31:11

标签: vb.net linq lambda expression-trees

我想实现这个功能:

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]'.

1 个答案:

答案 0 :(得分:2)

Public Function GetFunc(Of TSource, TResult) _
    selector As Expression(Of Func(Of TSource, TResult)) _
        As Func(Of TSource, TResult)
    Return selector.Compile()
End Function