New(list)
End Sub
Public Sub New(ByVal enumerable As IEnumerable(Of T))
MyBase.New()
For Each item As T In enumerable
Me.Add(item)
Next
End Sub
Public Sub New(ByVal enumerator As IEnumerator(Of T))
MyBase.New()
While enumerator.MoveNext()
Me.Add(enumerator.Current)
End While
End Sub
End Class
Public Class EntryPoint
Shared Sub Main()
Dim coll As MyCollection(Of Integer) = _
New MyCollection(Of Integer)(GenerateNumbers())
For Each n As Integer In coll
Console.WriteLine(n)
Next
End Sub
Shared Function GenerateNumbers() As IEnumerable(Of Integer)
Dim SomeNumbers As New MyCollection(Of Integer)
Dim i As Integer
For i = 4 To 0 Step -1
SomeNumbers.Add(i)
Next
Return SomeNumbers
End Function
End Class
Running the previous example will display the following output:
CHAPTER 10 n ARRAYS AND COLLECTIONS 210
4
3
2
1
0
In Main(), you can see the instance of MyCollection(Of Integer) created by passing in an
IEnumerable(Of Integer) type returned from the GenerateNumbers method. You don??™t create
constructors that accept the nongeneric IEnumerable and IEnumerator, simply because you
want to favor stronger type safety.
You may have noticed the existence of List(Of T) in the System.Collections.Generic
namespace. It would be tempting to use List(Of T) in your applications whenever you need
to provide a generic list type to consumers.
Pages:
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351