我正在尝试获得Expression(Of Func(Of T, TResult))
的结果,但我不确定Expressions是如何工作的。
这是我参与实验的地方
<Extension>
Public Function Test(Of T, TResult)(site As Object, expr As Expression(Of Func(Of T, TResult))) As Boolean
Dim result As Object = Nothing
result = Expression.Lambda(expr).Compile.DynamicInvoke
result = result()
End Function
这是我用来设置测试的代码。
Public Sub Main()
Dim dummy As Object = New Object
Dim result As Boolean = dummy.Test(Function(x As A) x.Bee.Tag)
End Sub
Public Class A
Public Property Bee As B = Nothing
End Class
Public Class B
Public Property Tag As Object = Nothing
End Class
请注意,此代码仅用于探索和学习。它绝对不会形成或准备好生产。
错误是
“System.MissingMemberException”类型的未处理异常 发生在Microsoft.VisualBasic.dll
附加信息:找不到类型'Func(Of。)的默认成员 A,对象)”
答案 0 :(得分:1)
首先,你应该停下来转动OPTION STRICT ON
。
真。每次。只需转动OPTION STRICT ON
即可。永远(除非你真的知道你正在做什么,你真的需要后期绑定)。
我并不是100%清楚你正在尝试做什么。另外,您无法为Object
编写扩展方法。
尽管如此,如果您想要在代码中运行一些东西,请看一下:
Sub Main
' create an object which we'll use in Test '
Dim obj = New A With { .Bee = New B With { .Tag = "Hello" }}
' call the Test function with an expression '
Dim result = Test(obj, Function(x As A) x.Bee.Tag)
Console.WriteLine(result)
End Sub
Public Class A
Public Property Bee As B = Nothing
End Class
Public Class B
Public Property Tag As Object = Nothing
End Class
Public Function Test(Of T, TResult)(obj As T, expr As Expression(Of Func(Of T, TResult))) As Boolean
' compiling the expression yields a function that creates a Func(Of T, TResult) '
' So let's create a Func(Of T, TResult) from the expression '
Dim result = DirectCast(Expression.Lambda(expr).Compile().DynamicInvoke(), Func(Of T, TResult))
' the Func(Of T, TResult) takes a T, so call it with obj '
Return result(obj).Equals("Hello")
End Function
这个示例仍然有点蹩脚,因为您可以在Func(Of T, TResult)
中使用Test
,但它会显示如何编译Expression
以创建Func(Of T, TResult)
,这可能是OPTION STRICT ON
稍后使用。
另外,转动{{1}}。