Prev | Current Page 401 | Next

Guy Fouch?©, Trey Nash

"Accelerated VB 2008"

Generics are dynamic as opposed to static in nature, so you
cannot achieve the same effect without some extra information. Whenever you hear the word
contract within the VB world, you may start thinking about interfaces. Therefore, we??™ve chosen
to have both of the shapes implement the IShape interface. Thus the IShape interface defines
the contract, and the shapes implement that contract. However, that still is not enough for the
compiler to be able to compile the previous code.
Generics must have a way to enforce the rule that the type T supports a specific contract
at run time, since constructed types are formed dynamically at run time. Another attempt to
solve the problem could look like the following:
Public Class Shapes(Of T)
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
'DON'T DO THIS!
Dim theShape As IShape = CType(shape, IShape)
acc += theShape.Area
Next shape
Return acc
End Get
End Property
Public Sub Add(ByVal shape As T)
shapes.Add(shape)
End Sub
End Class
CHAPTER 12 n GENERICS 253
This modification to Shapes(Of T) indeed does compile and work most of the time.
However, this generic has lost some value due to the type cast within the For Each loop.


Pages:
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
drzwiowe xiden.bosten.pl Marcin Wróbel Turcja 1 cosan.brene.pl