2017-05-11 43 views
2

我是VB.net的新手,目前正在编写一些常见构造的代码示例(这不会有任何意义),我可能需要在即将推出的项目中使用。我有lambda表达式一类为属性,它看起来像这样: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 

现在,当我尝试调用这些lambda表达式一些线工作,有的不会,我真的不知道为什么。

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 

我真的在这个行为难倒和不知道为什么这样的行为就这样,感谢您的任何建议要寻找什么,或解释。

+2

在VB.NET中(与C#不同),属性可以有参数。所以语法是不明确的,当你使用AddFromZeroUpTo(8)时,编译器认为你正在试图传递8给属性getter。你必须通过使用()(8)来解决模糊性,现在编译器确信你打算把8传递给委托。那么,清理这里窗口的语法。 –

回答

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)) 

注意,这个代码仅适用,如果你有选项严格上关闭您的项目。从许多角度来看,这是非常不明智的举动。