我是VB.net的新手,我正在编写一些常见构造的代码示例(这没有任何意义),我将在即将到来的项目中使用它。我有一个lambda表达式作为属性的类,如下所示:
Namespace SampleClasses
Public Class Lambdas
Public Shared ReadOnly Property AddFromZeroUpTo As Func(Of Integer, Integer)
Get
Return Function(upTo As Integer) Enumerable.Range(0, upTo + 1).Sum()
End Get
End Property
Public Shared ReadOnly Property ShowMessageBox As Action(Of String)
Get
Return Function(text As String) MessageBox.Show(text)
End Get
End Property
End Class
End Namespace
现在,当我尝试将那些lambdas称为有些线路时,有些线路不起作用,而且我真的不明白为什么。
SampleClasses.Lambdas.ShowMessageBox()(SampleClasses.Lambdas.AddFromZeroUpTo(8)) 'works
SampleClasses.Lambdas.ShowMessageBox(SampleClasses.Lambdas.AddFromZeroUpTo(8)) 'wont work
SampleClasses.Lambdas.AddFromZeroUpTo(8) 'wont work
SampleClasses.Lambdas.AddFromZeroUpTo()(8) 'works
Dim msg = SampleClasses.Lambdas.ShowMessageBox
msg(SampleClasses.Lambdas.AddFromZeroUpTo(8)) 'works
我真的很难过这种行为,并且不知道为什么这样做会这样,感谢任何建议要寻找或解释。
答案 0 :(得分:0)
ShowMessageBox和AddFromZeroUpTo都是属性。并且它们被定义为ReadOnly并返回某种代表。
因此,您将获得这些属性的值并调用返回的委托
你不能将任何东西传递给这些属性,就像它们是方法一样。
如果您添加隐含在您的通话中的Invoke方法,则
' Get the delegate returned and invoke it
Lambdas.ShowMessageBox.Invoke(Lambdas.AddFromZeroUpTo(8))
' Doesn't make sense. ShowMessageBox is a read only property
'Lambdas.ShowMessageBox(Lambdas.AddFromZeroUpTo(8)) 'wont work
' Use the delegate returned from AddFromZeroUp
Lambdas.AddFromZeroUpTo.Invoke(8)
' That's the same as above with the Invoke omitted
Lambdas.AddFromZeroUpTo()(8)
' First calls the delegate returned by
' AddFromZeroUpTo and with the return value calls the delegate returned
' by ShowMessageBox
Dim msg = Lambdas.ShowMessageBox
msg(Lambdas.AddFromZeroUpTo(8))
请注意,只有在项目中关闭Option Strict时,此代码才有效。从许多观点来看,这是一个非常不明智的举动。