Prev | Current Page 400 | Next

Guy Fouch?©, Trey Nash

"Accelerated VB 2008"

Area
Get
Return 3.1415 * radius * radius
End Get
End Property
End Class
Public Class Rect
Implements IShape
Private width As Double
Private height As Double
Public Sub New(ByVal width As Double, ByVal height As Double)
Me.width = width
Me.height = height
End Sub
Public ReadOnly Property Area() As Double Implements IShape.Area
Get
Return width * height
End Get
End Property
End Class
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
'THIS WON'T COMPILE!!!
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
CHAPTER 12 n GENERICS 252
Public Class EntryPoint
Shared Sub Main()
Dim shapes As Shapes(Of IShape) = New Shapes(Of IShape)()
shapes.Add(New Circle(2))
shapes.Add(New Rect(3, 5))
Console.WriteLine("Total Area: {0}", shapes.TotalArea)
End Sub
End Class
There is one major problem, as the code won??™t compile. The offending line of code is inside
the TotalArea property of Shapes(Of T). The compiler complains with the following error:
Error 1 'Area' is not a member of 'T'.
If this talk of requiring the contained type T to support the Area property sounds a lot like
a contract, that??™s because it is.


Pages:
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
wierszyki bajka Tango Olsztyn pozycjonowanie typy bukmacherskie