问题声明与vb.net行动(OF T)和lambda匿名方法
-
13-09-2019 - |
题
Imports System.Reflection
Public Class Test
Private Field As String
End Class
Module Module1
Sub Main()
Dim field = GetType(Test).GetField("Field", Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Instance)
Dim test = New Test
Dim GetValue = New Func(Of Test, String)(Function(t As Test) field.GetValue(test))
'This line indicates a compile error: 'Expression does not produce a value':
Dim SetValue = New Action(Of Test, String)(Function(t As Test, value As String) field.SetValue(test, value))
End Sub
End Module
Module Module2
Dim field = GetType(Test).GetField("Field", Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Instance) 'Is Shared (Module)
Sub Main2()
Dim test = New Test
Dim GetValue = New Func(Of Test, String)(Function(t As Test) field.GetValue(test))
Dim SetValue = New Action(Of Test, String)(Function(t As Test, value As String) field.SetValue(test, value))
End Sub
End Module
唐诺什么是错的,但单词数的作品好了!
解决方案
修改划伤我原来的答复,我误解了问题。
此不编译的原因是类型推理和后期绑定的问题。在第一个例子字段是一个局部变量,并因此可以参与类型推断。编译器将正确地推断出类型为字段信息。这意味着调用的SetValue是一种静态类型的呼叫。它是一个无效返回方法,因此是有功能lambda表达式这需要一个返回值不兼容。
在第二实施例的场值虽然是在模块级声明。这些变量不受类型推断,因此类型的对象将被选择。由于类型为对象,则调用的SetValue成为后期绑定的电话。所有后期绑定调用被假定为指向具有对象的返回类型的函数。在如果函数返回void运行时,没有什么实际上返回。所以在这种情况下它是一个非空返回表达,因此编译。
一个选择,你必须解决,这是明确类型字段作为第一个例子中的物体。这将迫使它是一个后期绑定呼叫它将编译就像第二个
Dim field As Object = ...
其他提示
那么这里是一个基于JaredPar的岗位最终的答案:
Module Module1
Sub Main()
Dim field = GetType(Test).GetField("Field", Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Instance)
Dim test = New Test
Dim GetValue = New Func(Of Test, String)(Function(t As Test) field.GetValue(test))
'This line indicates a compile error: 'Expression does not produce a value':
Dim SetValue = New Action(Of Test, String)(Function(t As Test, value As String) DirectCast(field, Object).SetValue(test, value))
End Sub
End Module
注意在铸造
到对象Dim SetValue = New Action(Of Test, String)(Function(t As Test, value As String) DirectCast(field, Object).SetValue(test, value))
不隶属于 StackOverflow