在vb.net中调用lambda中的子例程

时间:2009-10-07 07:27:57

标签: vb.net delegates lambda

我发现自己经常调用lambdas中的函数,因为提供的委托不匹配或没有足够的参数。令人恼火的是我不能在子程序上做lambda。每次我想要这样做时,我必须将我的子程序包装在一个不返回任何内容的函数中。不漂亮,但它的工作原理。

还有另一种方法可以让这更顺畅/更漂亮吗?

我已经读过,整个lambda的不足可能会在VS2010 / VB10中修复,所以我的问题更多是出于好奇。

一个简单的例子:

Public Class ProcessingClass
    Public Delegate Sub ProcessData(ByVal index As Integer)
    Public Function ProcessList(ByVal processData As ProcessData)
        ' for each in some list processData(index) or whatever'
    End Function
End Class

Public Class Main

    Private Sub ProcessingSub(ByVal index As Integer, _
                              ByRef result As Integer)
        ' (...) My custom processing '
    End Sub

    Private Function ProcessingFunction(ByVal index As Integer, _
                                        ByRef result As Integer) As Object
        ProcessingSub(index, result)
        Return Nothing
    End Function

    Public Sub Main()
        Dim processingClass As New ProcessingClass
        Dim result As Integer
        ' The following throws a compiler error as '
        ' ProcessingSub does not produce a value'
        processingClass.ProcessList( _
            Function(index As Integer) ProcessingSub(index, result))
        ' The following is the workaround that'
        ' I find myself using too frequently.'
        processingClass.ProcessList( _
            Function(index As Integer) ProcessingFunction(index, result))
    End Sub

End Class

2 个答案:

答案 0 :(得分:1)

如果您发现自己经常使用相同类型的数据,则可以将该委托包装在一个类中。

创建一个转换为委托的基类:

Public MustInherit Class ProcessDataBase
    Public Shared Widening Operator CType(operand As ProcessDataBase) as ProcessingClass.ProcessData
        Return AddressOf operand.Process
    End Sub

    Protected MustOverride Sub Process(index As Integer)  
End Class

继承自班级:

Public Class ProcessResult
    Inherits ProcessDataBase

    Public Result As Integer

    Protected Overrides Sub Process(index as Integer)
        ' Your processing, result is modified.
    End SUb
End Class

使用它:

Public Class Main()
    Public Sub Main()
        Dim processingClass As New ProcessingClass
        Dim processor As New ProcessResult

        processingClass.ProcessList(processor)
        Dim result as integer=processor.Result
    End Sub
End Class

答案 1 :(得分:0)

它在VB10中已修复,VS10 Beta为available,如果您可以选择使用它。在VB10中,你有没有返回值的lambdas,以及内联子/函数。

现在,也许你可以忘记lambdas并与代表合作?类似的东西:

processingClass.ProcessList(AddressOf ProcessingSub)