次の方法で共有


Generic implementation of IterateAndApply ( Query Design continued):

         This post is a part of a series of posts about query design. For the previous post see: https://blogs.msdn.com/vladimirsadov/archive/2007/01/14/reusability-is-the-reason-to-have-queries.aspx 

 

 

 

So far we have a pretty good implementation of IterateAndApply, but there are several issues with the code.

 

1) We are resorting to magic function ApplyCode.

2) IterateAndApply works with any list of integers. This is good, but what about lists of Doubles or a Queue or an Array?

 

Ok, #1 is a serious matter and we will just assume for now that magic method “just exists”. However supporting different types seems to be fairly easy – IterateAndApply can be generic function.

 

' source - the collection that is being iterated

' code - user supplied code to apply to each element

' returns a collection of results when user's code is applied to all

' elements.

    Function IterateAndApply(Of T)(ByVal source As IEnumerable(Of T), _

                              ByVal code As String) As IEnumerable(Of T)

        Dim result As New List(Of T)

        'iterate the source

        For Each item In source

            'apply the code that user has provided to each element

            result.Add(Apply(item, code))

        Next

        Return result

    End Function

'hypothetical function that applies given code to the given object and
'returns the result

    Function Apply(Of T)(ByVal item As T, _

                    ByVal code As String) As T

'todo: code gets “magically” applied to the item and result is returned

    End Function

 

The code above should handle all kinds of element types. In fact this function can iterate any collection as long as it implements IEnumerable(of T) . Upon execution of IterateAndApply and Apply the type of T will be inferred from the type of the source collection.

Comments