Just
imagine if you attempted to create a constructed type Shapes(Of Integer). The compiler
would happily oblige. But what would happen if you tried to get the TotalArea property from
a Shapes(Of Integer) instance? As expected, you would receive a runtime exception as the
TotalArea property accessor attempts to cast an Integer into an IShape. One of the primary
benefits of using generics is for better type safety, but in this example, you toss type safety
right out the window. So, what are you supposed to do? The answer lies in a concept called
generic constraints. Check out the following implementation:
Public Class Shapes(Of T As IShape)
Private shapes As List(Of T) = New List(Of T)()
Public ReadOnly Property TotalArea() As Double
Get
Dim acc As Double = 0
For Each shape As T In shapes
acc += shape.Area
Next shape
Return acc
End Get
End Property
Public Sub Add(ByVal shape As T)
shapes.Add(shape)
End Sub
End Class
Notice the extra clause in the first line of the class declaration using the As keyword. This
says, ???Define class Shapes(Of T) where T must implement IShape???. Now the compiler has
everything it needs to enforce type safety, and the JIT compiler has everything it needs to
build working code at run time. The compiler has been given a hint to help it notify you, with
a compile-time error, when you attempt to create constructed types where T does not implement
IShape.
Pages:
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414