从Expression中提取lambda?

问题描述:

我想实现这个功能:从Expression中提取lambda?

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

UPDATE

我有以下的问题,这是一个功能的一部分:

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

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

嗯,我想我写了错误的答案,你能帮我,我更新了我的问题。 – Shimmy 2010-08-09 07:53:12

+0

@Shimmy - 你的例外说你正在尝试使用'Func'的'Expression',就像它是'Func'一样。从'Func'的'Expresson'中获得'Func'的方法是调用'Compile'方法,如此答案所示。 – 2010-08-09 08:11:53

+0

我的问题是我没有设法找到编译,在明确投射到LambdaExpression后,我发现它。 – Shimmy 2010-08-09 08:29:10